Search code examples
iphonecore-animation

CoreAnimation CABasicAnimation, when to add the layer


I'm reading through Apple's documentation on CA, and I was trying to do a simple animation. I am wondering why this does not work:

CABasicAnimation *goRight = [CABasicAnimation animationWithKeyPath:@"position"];
goRight.duration = 5;
goRight.fromValue = [NSValue valueWithCGPoint:CGPointMake(0, 0)];
NSLog(@":%@", [goRight.fromValue description]);
goRight.toValue = [NSValue valueWithCGPoint:CGPointMake(100, 100)];
CALayer *thelayer = [CALayer layer];
[thelayer addAnimation:goRight forKey:nil];
[self.aView.layer addSublayer:thelayer];

but if I change the last few lines to:

//    CALayer *thelayer = [CALayer layer];
//    [thelayer addAnimation:goRight forKey:nil];
//    [self.aView.layer addSublayer:thelayer];
    [self.aView.layer addAnimation:goRight forKey:nil];

this works. I thought I read somewhere on SO that either implicit or explicit animations were off on the .layer property so I thought I should get in the practice of adding a sublayer to the main .layer property and have the animation act on that layer.

Can someone help explain what I am doing wrong? Thanks.


Solution

  • You're creating a brand new layer with no content and giving it an animation. There are two problems:

    1. The layer is size 0×0 by default, and you don't change its size. You need to make it bigger than 0×0 by setting either its frame or its bounds.
    2. The layer has no content or other properties that would make it visible. There are lots of ways to make it visible. One way is just to set its background color. For example:

      thelayer.backgroundColor = UIColor.redColor.CGColor;
      

    Also, when you add the animation to the layer, you should usually use the animated property name as the key. For example:

    [thelayer addAnimation:goRight forKey:@"position"];
    

    If you want to learn Core Animation, I highly recommend watching the WWDC videos. There are two videos, Core Animation in Practice parts 1 and 2, from WWDC 2010. There is one video, Core Animation Essentials, from WWDC 2011.