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;
}];
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
})
}
}
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With