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;
   }];
user3250926
  • 127
  • 1
  • 2
  • 7
  • I edited my original question to include an example of Objective-C – user3250926 Dec 05 '14 at 18:28
  • Does this answer your question? [How to animate the textColor property of an UILabel?](https://stackoverflow.com/questions/2426614/how-to-animate-the-textcolor-property-of-an-uilabel) – aheze May 18 '21 at 18:10

2 Answers2

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
        })
    }
}
Dennis Weidmann
  • 1,942
  • 1
  • 14
  • 16
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

aheze
  • 24,434
  • 8
  • 68
  • 125