UILabel text color animation in Swift

How can I animate a UILabel color change using swift? I have seen people mention the use of CALayer, but I cannot understand 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;
   }];
+4
source share
2 answers

it's a lot easier than working with CALayer

let myLabel: UILabel!

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

Here it is...

Edit

Okay, sorry, I didn’t know what color you want to change ... I converted your example into quick code ...

the 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
        })
    }
}
+12
source

Animate a color or text change in UILabel with swift, my extension.

extension UILabel {
    /**
     Set Text With animation

     - parameter text:     String?
     - parameter duration: NSTimeInterval?
     */
    public func setTextAnimation(text: String? = nil, color: UIColor? = nil, duration: NSTimeInterval?, completion:(()->())? = nil) {
        UIView.transitionWithView(self, duration: duration ?? 0.3, options: .TransitionCrossDissolve, animations: { () -> Void in
            self.text = text ?? self.text
            self.textColor = color ?? self.textColor
            }) { (finish) in
                if finish { completion?() }
        }
    }
}

Use for color:

self.label.setTextAnimation(color: UIColor.whiteColor(), duration: 0.15)
+1
source

All Articles