Trying to animate a backgroundcolor on uilabel to achieve a fade effect, but it is applied instantly

I'm trying to animate the backgroundcolor on uilabel to achieve a fade effect. My code is as follows:

UILabel *lbl = ... UIColor *oldCol = lbl.backgroundColor; lbl.backgroundColor = [UIColor blueColor]; [UIView animateWithDuration:1.0 animations:^(void) { lbl.backgroundColor = oldCol; }]; 

But it instantly returns to its original color. I also tried the following to isolate the problem:

 lbl.backgroundColor = [UIColor blueColor]; [UIView animateWithDuration:1.0 animations:^(void) { lbl.backgroundColor = [UIColor greenColor]; }]; 

And it instantly turns green. Any ideas?

+4
source share
2 answers

UILabel's background color is not animated. See How to animate the background color of UILabel? for a possible workaround.

+4
source

UILabel background UILabel not animated, but UILabel background UILabel . Therefore, do not set the foreground color, otherwise it will hide the color of the layer. Just make the main background transparent so that the layer shows.

 myLabel.backgroundColor = UIColor.clearColor() 

If you need to set the initial color, you can do it as follows:

 myLabel.layer.backgroundColor = UIColor.blueColor().CGColor 

Then, to animate this color to a new one, you can do the following:

 UIView.animateWithDuration(1.0, animations: { self.myLabel.layer.backgroundColor = UIColor.redColor().CGColor }) 

This answer is in Swift, but the idea is the same.

0
source