Reputation: 2933
I have an UIImageView
spinning using the following code:
CABasicAnimation *rotation;
rotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
rotation.fromValue = [NSNumber numberWithFloat:0];
rotation.toValue = [NSNumber numberWithFloat:(2*M_PI)];
rotation.duration = 2.0;
rotation.repeatCount = HUGE_VALF;
[myView.layer addAnimation:rotation forKey:@"Spin"];
And I can stop it by running
[myView.layer removeAnimationForKey:@"Spin"];
However, when the animation stops, the image resets to where it started. This looks a little awkward if the image is mid-turn, so I would like for it to stop exactly where it is in the rotation. I assume this would require getting the current rotation amount just before stopping the animation, and then setting it back to that rotation amount instantly after stopping the animation. I do not know how to do this though.
Upvotes: 2
Views: 2043
Reputation: 130222
There a couple ways of doing this. One way is my affecting the layers speed property which you can find an example of in the answer to this post: Is there a way to pause a CABasicAnimation?. But this way is more of a means to pause the animation.
Since you want to stop it, I recommend you keep calling removeAnimationForKey: like you are, and coupling it with a CATransform3D made to match the view's presentationLayer's transform before it stopped animating. Give it a try:
CATransform3D myTransform = [(CALayer*)[myView.layer presentationLayer] transform];
[myView.layer removeAnimationForKey:@"Spin"];
[myView.layer setTransform:myTransform];
Upvotes: 6