Animate UILabel text between two numbers?

Markus Kasten picture Markus Kasten · Mar 14, 2011 · Viewed 35.8k times · Source

I'm new to iPhone and Mac programming (developed for Windows before), and I've got a question:

How do I animate the text property of an UILabel between two numbers, e.g. from 5 to 80 in an Ease-Out style? Is it possible with CoreAnimation? I have been searching on Google for an hour, but I haven't found anything solving my problem. What I want: Animate the users money for a simple game. It doesn't look very nice when it just goes from 50 to 100 or something like that without animation.

Anyone having an idea how to do that?

Thanks!

Answer

CedricSoubrie picture CedricSoubrie · Jun 7, 2011

You can use the automatic transitions. It's working perfectly well :

// Add transition (must be called after myLabel has been displayed)
 CATransition *animation = [CATransition animation];
animation.duration = 1.0;
animation.type = kCATransitionFade;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[myLabel.layer addAnimation:animation forKey:@"changeTextTransition"];

// Change the text
myLabel.text = newText;

This code works if myLabel is already displayed. If not myLabel.layer will be nil and the animation will not be added to the object.


in Swift 4 that would be:

let animation: CATransition = CATransition()
animation.duration = 1.0
animation.type = kCATransitionFade
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
myLabel.layer.add(animation, forKey: "changeTextTransition")