在Swift中为UILabel文本颜色设置动画

use*_*926 4 iphone calayer uilabel ios swift

如何使用swift为UILabel的颜色变化设置动画?我见过人们提到使用CALayer,但我无法弄清楚Swift的语法.

这是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;
   }];
Run Code Online (Sandbox Code Playgroud)

Den*_*ann 12

它比使用CALayer容易得多

let myLabel: UILabel!

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

而已...

编辑

好的,对不起,我不知道你要改变什么颜色...我已经将你的例子转换为快速代码......

第一

import QuartzCore
Run Code Online (Sandbox Code Playgroud)

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
        })
    }
}
Run Code Online (Sandbox Code Playgroud)