我正在尝试为标签文本制作动画,如果值较大,它将把文本颜色更改为蓝色,如果值较小,它将颜色更改为红色,否则保持相同的“黑色”。
但是 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/