Animate UILabel text color in Swift
Asked Answered
K

2

5

How can I animate a color change of UILabel using swift? I have seen people mention using CALayer but I cannot figure out the Swift syntax.

This is an example of Objective-C

CALayer *layer = myView.layer;
CATextLayer *textLayer = [CATextLayer layer];
[textLayer setString:@"My string"];
[textLayer setForegroundColor:initialColor;
[textLayer setFrame:self.bounds];
[[self.view layer] addSublayer:textLayer];

[UIView animateWithDuration:0.5 animations:^{
     textLayer.foregroundColor = finalColor;
   }];
Krishnakrishnah answered 5/12, 2014 at 18:6 Comment(2)
I edited my original question to include an example of Objective-CKrishnakrishnah
Does this answer your question? How to animate the textColor property of an UILabel?Madder
R
14

it is much easier than working with CALayer

let myLabel: UILabel!

UIView.animateWithDuration(2, animations: { () -> Void in
     myLabel.backgroundColor = UIColor.redColor();
})

Thats it...

Edit

Ok, sorry I didn't knew what color you want to change... I have converted your example to swift code...

first

import QuartzCore

than

if let layer: CALayer = self.view.layer as CALayer? {
    if let textLayer = CATextLayer() as CATextLayer? {
        textLayer.string = "My string"
        textLayer.foregroundColor = UIColor.whiteColor().CGColor
        textLayer.frame = self.view.bounds
        self.view.layer.addSublayer(textLayer)

        UIView.animateWithDuration(0.5, animations: { () -> Void in
            textLayer.foregroundColor = UIColor.redColor().CGColor
        })
    }
}
Rockie answered 5/12, 2014 at 18:22 Comment(7)
The text color changes but it does not animate. It changes instantly.Krishnakrishnah
backgroundColor ≠ textColor, and as the question’s author points out, this doesn’t actually workSarnoff
Thanks, sorry can't vote you up cause I don't have 15 reputationKrishnakrishnah
At first, my first answer works... I checked it in Xcode, so first check it Noah, than write such stuff... At second, he edited his post, at my first answer I didn't know that the text color is meant... Now I have edited my post too, to fit his expectationsRockie
A down vote just because a lack of your knowledge... Nice work dudeRockie
user, you need to change the objects from self.view to your Label... But I guess you already saw this? :-)Rockie
First code snippet does't change the text color, which is actually what the author asked for and the second code doesn't work for me.Pundit
M
2

Unfortunately, textColor isn't animatable via UIView.animate. However, UIView.transition works.

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    
    UIView.transition(with: label, duration: 2, options: .transitionCrossDissolve) {
        self.label.textColor = .green
    }
}

Result:

Label's text color fades from black to green

Madder answered 18/5, 2021 at 18:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.