views:

56

answers:

4

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];
    }];
A: 

Here is the reference:

animations A block object containing the changes to commit to the views. This is where you programmatically change any animatable properties of the views in your view hierarchy. This block takes no parameters and has no return value. This parameter must not be NULL

What I understand about this is when your view call the animation block, then your view label background color is commited to be green since that time. Then, if you don't change the label background color to something else, then it will always be green. This is what I guess

vodkhang
+1  A: 

First of all, I have not tried this out my self, but I've given it some thought in the last weeks. I guess, that the color-property of your view cannot be animated, like i.e. "hidden", changes will appear at once. A possible solution would be, to overlay two labels the upper one with your old color, the one below with the new one. Then you could simply fade the upper one out. I'm not sure though, if the blending will look nicely.

Phlibbo
+1  A: 

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];
bosmacs
This works, thank you! I'd still like to know why a UIView works, and a UILabel doesn't, after all, a UILabel is a UIView.
Michiel de Mare
Agreed. I can only assume at this point that Apple chose to make those properties non-animated for `UILabel`. FWIW, `UIButton` behaves the same way as the label.
bosmacs
+1  A: 

Do the color animation manually, based off of an NSTimer or CADisplayLink callback at some reasonable frame rate (say 20 fps). You will have to calculate your own color change curve in RGB or HSV based on the fractional elapsed time over the full animation time (2.0 seconds in your example), or use an array of 40 intermediate colors.

hotpaw2