简体   繁体   中英

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 (eg 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

PS I'd like to stick to CA as much as possible.

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)

    }
}

You can achieve that using core animation. You can add animation to your label. Try out following

CATransition *textAnimation = [CATransition animation];
textAnimation.type = kCATransitionMoveIn;
textAnimation.duration = 0.5;
textAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[numLabel.layer addAnimation:textAnimation forKey:@"changeTextTransition"];

You can change your label text anytime later on adding animation and it will animate.

numLabel.text = "1";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM