How to animate the background color of a UILabel?

Michiel de Mare picture Michiel de Mare · Sep 21, 2010 · Viewed 49.3k times · Source

This looks like it should work, but doesn't. The color turns green at once.

self.labelCorrection.backgroundColor = [UIColor whiteColor];
[UIView animateWithDuration:2.0 animations:^{
    self.labelCorrection.backgroundColor = [UIColor greenColor];
}];

Answer

bosmacs picture bosmacs · Sep 21, 2010

I can't find it documented anywhere, but it appears the backgroundColor property of UILabel is not animatable, as your code works fine with a vanilla UIView. This hack appears to work, however, as long as you don't set the background color of the label view itself:

#import <QuartzCore/QuartzCore.h>

...

theLabel.layer.backgroundColor = [UIColor whiteColor].CGColor;

[UIView animateWithDuration:2.0 animations:^{
    theLabel.layer.backgroundColor = [UIColor greenColor].CGColor;
} completion:NULL];