Search code examples
ioscore-animationcalayer

What is preventing the sublayer from moving with parent?


Using the code below, sublayer1 & sublayer2 are drawn where desired. When the animation occurs, sublayer1 moves as expected, while sublayer2 move up-left initially and then down-right. (2 doesn't remain in same place within 1)

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // Create a blue sublayer 
    sublayer1 = [CALayer layer];
    sublayer1.backgroundColor = [[UIColor blueColor] CGColor];
    sublayer1.frame = CGRectMake(30, 30, 120, 190);
    sublayer1.position = CGPointMake(90, 130);
    [self.view.layer addSublayer:sublayer1];

    // Create a sublayer within blue layer
    CALayer *sublayer2 = [CALayer layer];
    sublayer2.bounds = CGRectMake(0, 0, 60, 60);
    sublayer2.frame = CGRectMake(30, 50, 60, 60);
    sublayer2.contents = (id)[[UIImage imageNamed:@"sun.png"] CGImage];
    [sublayer1 addSublayer:sublayer2];

    [self performSelector:@selector(moveBlueLayer) withObject:nil afterDelay:1.0];
}

- (void)moveBlueLayer
{
    // Create a new position for animation to move to
    CGPoint endPostition = CGPointMake(190, 285);

    [CATransaction setAnimationDuration:4];
    sublayer1.bounds = CGRectMake(130, 190, 120, 190);
    sublayer1.position = endPostition;
}

Aren't they supposed to move together? Any ideas why they don't? I am trying to stick with solutions to the 'implicit' animation for now.


Solution

  • The line 3rd up from the bottom was causing the erratic behavior.

    - (void)moveBlueLayer
    {
       // Create a new position for animation to move to
       CGPoint endPostition = CGPointMake(190, 285);
    
       [CATransaction setAnimationDuration:4];
       // Next line causing the problem
       // sublayer1.bounds = CGRectMake(130, 190, 120, 190);
       sublayer1.position = endPostition;
    }