Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to animate the textColor property of an UILabel?

For some reason, when I try to animate textColor, it won't work. The textColor just suddenly changes from A to B. Is it possible to animate it, for example, red to black?

like image 531
dontWatchMyProfile Avatar asked Mar 11 '10 16:03

dontWatchMyProfile


3 Answers

Instead, have you tried using a crossfade transition on the object itself like this, it'll give you a nice fade-in fade-out effect from one color to another:

Objective C

[UIView transitionWithView:myLabel duration:0.25 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
    myLabel.textColor = NEW_COLOR;
} completion:^(BOOL finished) {
}];

Swift 5

UIView.transition(with: creditsLabel, duration: 0.25, options: .transitionCrossDissolve) {
    self.creditsLabel.textColor = .red
}

This is better than using NSTimers, CATextLayers and so on so forth for various reasons. CATextLayer does not have proper support for text kerning or NSAttributedText, and NSTimers are laggy (plus there's too much code). The transition animation above does the trick, and also can be used in a chain animation. I had the same issue and have already tried the solutions above but this simple code works wonders instead.

like image 105
strange Avatar answered Nov 15 '22 08:11

strange


Swift 4 solution:

UIView.transition(with: yourLabel, duration: 0.3, options: .transitionCrossDissolve, animations: {
  self.yourLabel.textColor = .red
}, completion: nil)
like image 43
budiDino Avatar answered Nov 15 '22 09:11

budiDino


The reason that textColor is not animatable is that UILabel uses a regular CALayer instead of a CATextLayer.

To make textColor animatable (as well as text, font, etc.) we can subclass UILabel to make it use a CATextLayer.

This is quite a lot of work, but luckily I already did it :-)

You can find a complete explanation + a drop-in open source replacement for UILabel in this article

like image 13
adamsiton Avatar answered Nov 15 '22 07:11

adamsiton