Search code examples
iphoneobjective-ccocoa-touchuikitcore-animation

CATransaction is immediate and ignore the transition time


I can't figure out why this code:

CALayer *viewLayer = [aView layer];
[CATransaction begin];
[CATransaction setValue:[NSNumber numberWithFloat:10.0f]
                 forKey:kCATransactionAnimationDuration];
viewLayer.position = CGPointMake(200.0f, 200.0f);
viewLayer.position = CGPointMake(320.0f, 480.0f);

[CATransaction commit];

move the view but the movement is not animated ( the movement is immediate ). The aView is a UIImageView inside a UIView.


Solution

  • Implicit actions are disabled for layers associated with views. A view is always the delegate of its own layer, and it implements -actionForKey: to disable implicit animations and only add animations inside of a UIView animation block. Your best bet is to simply use explicit CABasicAnimations. Assuming you want to animate from that first point to the second, you can use something like

    CALayer *layer = aView.layer;
    
    layer.position = CGPointMake(320, 480); // final position
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position"];
    anim.fromValue = [NSValue valueWithCGPoint:CGPointMake(200, 200)];
    anim.toValue = [NSValue valueWithCGPoint:layer.position]; // I believe this line is optional, it should default to current position
    [layer addAnimation:anim forKey:@"position"];