TIMEX TIMEX - 2 months ago 18x
iOS Question

How to animate (fade) UILabel textColor in Swift?

UIView.animateWithDuration(self.fadeTime, delay: 0,
options: UIViewAnimationOptions.AllowUserInteraction,
animations: { [weak self] () -> Void in
var randomIndex = Int(arc4random_uniform(UInt32(CONSTANTS.MainColorScheme.count)))
self?.startButton.titleLabel!.textColor = CONSTANTS.MainColorScheme[randomIndex]
}) { (stuff Bool) -> Void in

This doesn't seem to work...it just "jumps" to the next color. It doesn't fade.
However, if I apply the same approach to
, my code works.

Is there an alternative?


UILabel.textColor does not support animation. But you can animate CATextLayer:


let textLayer = CATextLayer()
textLayer.string = "Your text"
textLayer.foregroundColor = yourFirstColor
textLayer.frame = yourButton.bounds

UIView.animateWithDuration(1) {
    textLayer.foregroundColor = yourSecondColor

Objective C:

CATextLayer *textLayer = [CATextLayer layer];
[textLayer setString:@"Your text"];
[textLayer setForegroundColor:yourFirstColor];
[textLayer setFrame:yourButton.bounds];
[[yourButton layer] addSublayer:textLayer];

[UIView animateWithDuration:1 animations:^{
     textLayer.foregroundColor = yourSecondColor;