Search code examples
iosswiftcore-animationuiviewanimationcabasicanimation

How would one animate UILabel text property with CoreAnimation in Swift?


I want to increment UILabel.text value from 0 to say 100 using CoreAnimation with easing functions (e.g. easeInOutQuad). But it seems like text property is not animatable. So how to achieve this with the help of CA? Or Would I need to implement easing function myself and call it using GCD? Thanks

P.S. I'd like to stick to CA as much as possible.


Solution

  • class ViewController: UIViewController {
    
        @IBOutlet weak var label: UILabel!
    
        var counter = 0
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("animate"), userInfo: nil, repeats: true)
            timer.fire()
        }
    
        func animate() {
            UIView.transitionWithView(label,
                                  duration: 1.0,
                                  options: [.CurveEaseInOut],
                                  animations: { () -> Void in
                                    self.counter += 1
                                    self.label.text = "\(self.counter)"
            }, completion: nil)
    
        }
    }