views:

809

answers:

2

I want to remove an animation (CABasicAnimation) before it has completed.

For example:

In my code, I start a needle animating from a rotation value of 0 to a target value of 5. How do I stop the animation when the needle reaches a rotation value of 3?

CALayer* layer = someView.layer;
CABasicAnimation* animation;
animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
animation.fromValue = [NSNumber numberWithFloat:0];
animation.toValue = [NSNumber numberWithFloat:5];
animation.duration = 1.0;
animation.cumulative = YES;
animation.repeatCount = 1;
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
[layer addAnimation:rotationAnimation forKey:@"transform.rotation.z"];
A: 

Change:

animation.toValue = [NSNumber numberWithFloat:5];

to

animation.toValue = [NSNumber numberWithFloat:3];

AlBlue
I presume he means conditionally stop the animation at 3.
willc2
A: 

You can monitor the current value of the transformation by looking at the presentationLayer attribute on the CALayer. The presentation layer holds the current values mid-animation.

IE:

CALayer *pLayer = [layer presentationLayer];
NSLog(@"Currently at %@", [pLayer valueForKeyPath:@"transform.rotation.z"]);

To stop the animation at 3, I would grab the layer, remove the 0-5 animation, start a new animation using the fromValue out of the presentationLayer and the toValue of 3. Setting the duration of the animation depends on the behavior of the animation, but if you want the animation to take 3/5's of a second to complete if it stops at 3, then you would find how far into the animation you are by looking at how far into the 0-5 animation you are, then subtracting that from 3/5's of a second to get the remainder of time you want to use.

I learned a ton on CoreAnimation from Marcus Zarra at the Voices That Matter iPhone conference. I'd recommend following his blog and buying his book!

Brian King