Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change label color with animateWithDuration in Swift

Tags:

ios

uilabel

swift

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()
like image 397
Mohamed Horani Avatar asked Dec 24 '22 18:12

Mohamed Horani


1 Answers

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()
}
like image 119
Sandeep Avatar answered Dec 27 '22 07:12

Sandeep