Animate UILabel text color in Swift
12,586
Solution 1
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
})
}
}
Solution 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:
Related videos on Youtube
Author by
user3250926
Updated on September 14, 2022Comments
-
user3250926 over 1 year
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; }];
-
user3250926 over 9 yearsThe text color changes but it does not animate. It changes instantly.
-
Noah Witherspoon over 9 yearsbackgroundColor ≠ textColor, and as the question’s author points out, this doesn’t actually work
-
user3250926 over 9 yearsThanks, sorry can't vote you up cause I don't have 15 reputation
-
Dennis Weidmann over 9 yearsAt 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 expectations
-
Dennis Weidmann over 9 yearsA down vote just because a lack of your knowledge... Nice work dude
-
Dennis Weidmann over 9 yearsuser, you need to change the objects from self.view to your Label... But I guess you already saw this? :-)
-
Raphael about 9 yearsFirst 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.