[英]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.