Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate UILabel text color in Swift

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;
   }];
like image 422
user3250926 Avatar asked Dec 05 '14 18:12

user3250926


2 Answers

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
        })
    }
}
like image 160
Dennis Weidmann Avatar answered Oct 31 '22 10:10

Dennis Weidmann


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

like image 36
aheze Avatar answered Oct 31 '22 10:10

aheze