Search code examples
iosanimationcore-animationcalayer

Why view.layer.backgroundColor = randomColor won't animate the color change?


When I trying to set view.layer.backgroundColor, the color changes immediately without animation. But if I create a CALayer, add it as the sublayer of view.layer, and change the backgroundColor of that CALayer, I can see the implicit color change animation. Can anyone explain why there is no animation when changing view.layer.backgroundColor ?

\\ add CALayer
self.colorLayer = [CALayer layer];
self.colorLayer.frame = CGRectMake(50.0f, 50.0f, 100.0f, 100.0f);
self.colorLayer.backgroundColor = [UIColor blueColor].CGColor;
[self.view.layer addSublayer:self.colorLayer];

\\change the color somewhere else
CGFloat red = arc4random() / (CGFloat)INT_MAX;
CGFloat green = arc4random() / (CGFloat)INT_MAX;
CGFloat blue = arc4random() / (CGFloat)INT_MAX;
self.colorLayer.backgroundColor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0].CGColor; // can animate
self.view.layer.backgroundColor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0].CGColor; // won't animate

Solution

  • From Core Animation Programming Guide:

    Because iOS views always have an underlying layer, the UIView class itself derives most of its data from the layer object directly. As a result, changes you make to the layer are automatically reflected by the view object as well. This behavior means that you can use either the Core Animation or UIView interfaces to make your changes.

    If you want to use Core Animation classes to initiate animations, you must issue all of your Core Animation calls from inside a view-based animation block. The UIView class disables layer animations by default but reenables them inside animation blocks. So any changes you make outside of an animation block are not animated.

    (Emphasis added.)