[英]Change label color with animateWithDuration in 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()
}
我也尝试使用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()
}
基于Acluda的答案,我建议将他的代码放在animateWithDuration的完成处理程序中:动画:完成变体。
UIView.animateWithDuration(2,
animations: { () -> Void in self.label.textColor = UIColor.blueColor(); },
completion: { (wentThrough: Bool) -> Void in
{ UIView.animateWithDuration(2,
animations: { () -> Void in self.label.textColor = UIColor.blackColor(); }) })
UIView.transitionWithView(myLabel, duration: 0.25, options: .TransitionCrossDissolve, animations: {() -> Void in
label.textColor = UIColor.redColor()
}, completion: {(finished: Bool) -> Void in
})
试试:)
第一个动画完成后,没有任何逻辑告诉UIView返回UIColor.blackColor。
考虑在动画调用蓝色/红色后添加此项。
UIView.animateWithDuration(2,animations:
{ () -> Void in self.label.textColor = UIColor.blackColor(); })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.