Change label color with animateWithDuartion Swift

I am trying to animate the text of a label so that if the value is greater it will change the text color to blue and if the value is less then it will change the color to red otherwise it will remain the same "Black" color.

But UIView.animateWithDuration()

it changes color to blue all the time, all I am trying to do is if the value is large or less, I want to change the color of the label to blue or red for a few seconds and then return it 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 the function Sleep

as below but it didn't work

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

      

+3


source to share


4 answers


animation UIView api cannot animate textColor property for UILabel, you will need to use CAAnimation for that. Here is an 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()
}

      

+4


source


Building on Acluda's answer, I would recommend putting his code in an animation completion handler: continuation option: animation: completion.



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

      

+1


source


UIView.transitionWithView(myLabel, duration: 0.25, options: .TransitionCrossDissolve, animations: {() -> Void in
            label.textColor = UIColor.redColor()
        }, completion: {(finished: Bool) -> Void in
        })

      

Try :)

+1


source


There is no logic that tells UIView to return to UIColor.blackColor after the first animation finishes.

Consider adding this after calling the animation for blue / red.

UIView.animateWithDuration(2,animations:
        { () -> Void in self.label.textColor = UIColor.blackColor(); })

      

0


source







All Articles