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

标签 ios swift uilabel

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

但是 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()
}

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

self.label.textColor = UIColor.blueColor()
sleep(3)
self.label.textColor = UIColor.blackColor()

最佳答案

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

关于ios - 在 Swift 中使用 animateWithDuration 更改标签颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30578185/

相关文章:

ios - 如何在 iOS/Swift 中创建指定宽度的固定宽度标签?

ios - 覆盖 UILabel 的布局以添加带有手势处理的 subview

iphone - Interface Builder 文件中的未知类 ZBarReaderView

ios - Interface Builder 文件中的未知类 ****

ios - Swift 3 中的 CAShapeLayer 点击检测

ios - 如何在 UITableViewCell 中的 UILabel 中设置背景图片

iphone - 如何在 UILabel 中垂直居中嵌入字体?

ios - 如何一次只为一个单元格显示 UITableViewCell 的 accessoryType 属性?

ios - 为什么每当我加载 UIImagePickerController View 时都会加载我的键盘?

ios - 如何在 Xcode 7 中将四个按钮对齐死点?