I\'m trying to construct a CABasicAnimation to animate the backgroundColor property of a Core Animation CALayer, but I can\'t figure out how to properly wrap a CGColorRef va
You don't need to wrap CGColorRef
s when setting the toValue
or fromValue
properties of a CABasicAnimation
. Simply use the CGColorRef
. To avoid the compiler warning, you can cast the CGColorRef
to an id
.
In my sample app, the following code animated the background to red.
CABasicAnimation* selectionAnimation = [CABasicAnimation
animationWithKeyPath:@"backgroundColor"];
selectionAnimation.toValue = (id)[UIColor redColor].CGColor;
[self.view.layer addAnimation:selectionAnimation
forKey:@"selectionAnimation"];
However, when the animation is over, the background returns to the original color. This is because the CABasicAnimation
only effects the presentation layer of the target layer while the animation is running. After the animation finishes, the value set in the model layer returns. So you are going to have to set the layers backgroundColor
property to red as well. Perhaps turn off the implicit animations using a CATransaction
.
You could save yourself this trouble by using an implicit animation in the first place.
I was struggling with this problem until I experimentally found the roadblock. Setting the backgroundColor property of the layer, either directly or via the animation, will have no effect if you change the background color from the default (of unspecified) in Interface Builder, in the context of course of an item (such as UILabel) that's been placed in IB. So leave the background color unspecified and the above should work.