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

时间:2014-12-05 18:06:54

标签: ios iphone swift uilabel calayer

如何使用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;
   }];

2 个答案:

答案 0 :(得分:11)

比使用CALayer

容易得多
let myLabel: UILabel!

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

多数民众赞成......

修改

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

首先

import QuartzCore

大于

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
        })
    }
}

答案 1 :(得分:0)

不幸的是,textColor 不能通过 UIView.animate 设置动画。但是,UIView.transition 有效。

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    
    UIView.transition(with: label, duration: 2, options: .transitionCrossDissolve) {
        self.label.textColor = .green
    }
}

结果:

Label's text color fades from black to green