在 Swift 中使用 animateWithDuration 更改标签颜色

Moh*_*ani 4 uilabel ios swift

我正在尝试为标签文本设置动画,以便如果值较大,它将文本颜色更改为蓝色,如果值较小,则将颜色更改为红色,否则保持相同的“黑色”。

但是UIView.animateWithDuration()它将颜色永久更改为蓝色,我想要做的就是如果值大于或小于,我想将标签颜色更改为蓝色或红色几秒钟,然后将其颜色恢复为黑色。

这是我的代码:

@IBOutlet weak var label: UILabel!
let x = 10
let y = 20

if x > y 
{
UIView.animateWithDuration(2,animations:
            { () -> Void in self.label.textColor = UIColor.blueColor(); })
}

else if y < x
{
UIView.animateWithDuration(2,animations:
                    { () -> Void in self.label.textColor = UIColor.redColor(); })
}
else
{
 self.label.textColor = UIColor.blackColor()
}
Run Code Online (Sandbox Code Playgroud)

我也尝试使用如下Sleep功能,但没有成功

self.label.textColor = UIColor.blueColor()
sleep(3)
self.label.textColor = UIColor.blackColor()
Run Code Online (Sandbox Code Playgroud)

San*_*eep 7

UIView 动画 api 不能为 UILabel 的 textColor 属性设置动画,为此您需要使用 CAAnimation。这是使用 CATransition 的实现。

 func animate() {
    let x = 10
    let y = 20

    var finalColor: UIColor!

    if x > y {
        finalColor = UIColor.blueColor()
    } else {
        finalColor = UIColor.redColor()
    }

    let changeColor = CATransition()
    changeColor.type = kCATransitionFade
    changeColor.duration = 2.0

    CATransaction.begin()

    CATransaction.setCompletionBlock {
        self.label.textColor = UIColor.blackColor()
        self.label.layer.addAnimation(changeColor, forKey: nil)
    }
    self.label.textColor = finalColor
    self.label.layer.addAnimation(changeColor, forKey: nil)

    CATransaction.commit()
}
Run Code Online (Sandbox Code Playgroud)