How to remove animation (CABasicAnimation)?
I want to remove an animation (CABasicAnimation) before it finishes.
For example:
In my code, I start animating the needle 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"];
You can control the current transform value by looking at the presentationLayer attribute on the CALayer. The presentation layer contains the current mid-animation values.
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 fromValue from presentationLayer and toValue from 3. Setting the animation duration depends on the animation's behavior, but if you want the animation to take 3/5 seconds to complete, if it stops at 3, you can find how far you are in the animation by looking at how far in the 0-5 animation you are, then subtracting that from 3/5 of a second to get the remaining time you are want to use.
I learned a ton on CoreAnimation from Marcus Zarra at the Voices That Matters iPhone conference. I would recommend following his blog and buying his book.
source to share