Reputation: 554
I'm trying to animate a label text so that if the value greater it will change the text color to blue and if the value less it will change the color to Red, else remain the same "Black color".
But UIView.animateWithDuration()
it change the color to Blue permanently, all I am trying to do is if the value great or less than, I want to change the label color to blue or red for few seconds then return its color to black.
Here is my code:
@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()
}
also I tried to use Sleep
function as follow but it didn't work out
self.label.textColor = UIColor.blueColor()
sleep(3)
self.label.textColor = UIColor.blackColor()
Upvotes: 4
Views: 3451
Reputation: 1741
UIView.transitionWithView(myLabel, duration: 0.25, options: .TransitionCrossDissolve, animations: {() -> Void in
label.textColor = UIColor.redColor()
}, completion: {(finished: Bool) -> Void in
})
Try :)
Upvotes: 1
Reputation: 21144
UIView animation api cannot animate the textColor property of UILabel, for that you will need to use CAAnimation. Here is a implementation using 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()
}
Upvotes: 8
Reputation: 71
Building on Acluda's answer, I'd recommend putting his code in the completion handler of the animateWithDuration:animations:completion variant.
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(); }) })
Upvotes: 2
Reputation: 344
There is no logic that tells the UIView to return back to UIColor.blackColor once the first animation is complete.
Consider adding this after animation calls for blue/red.
UIView.animateWithDuration(2,animations:
{ () -> Void in self.label.textColor = UIColor.blackColor(); })
Upvotes: 0