在 Swift 中动画 UILabel 文本颜色 [英] Animate UILabel text color in Swift

查看:45
本文介绍了在 Swift 中动画 UILabel 文本颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 swift 为 UILabel 的颜色变化设置动画?我看到有人提到使用 CALayer,但我无法弄清楚 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.

这是一个Objective-C的例子

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;
   }];

推荐答案

比使用 CALayer 容易多了

it is much easier than working with CALayer

let myLabel: UILabel!

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

就是这样...

编辑

好的,抱歉,我不知道您要更改什么颜色...我已将您的示例转换为 swift 代码...

Ok, sorry I didn't knew what color you want to change... I have converted your example to swift code...

第一次

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

这篇关于在 Swift 中动画 UILabel 文本颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆