TIMEX TIMEX - 3 months ago 22
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
self.view.backgroundColor
, my code works.

Is there an alternative?

Answer

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

Swift:

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

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;
}];