Search code examples
cocoacore-animation

how to stop an animation but make it finish the current animation


I make a animation and make it runs it forever. And now I want to stop it after clicking a button. Then animation is rotating a image of a button from 0 to 360 degree. I'd like to stop the animation but make the animation to finish the current cycle. For example, if the button is rotated at 200 degree, and I click the stop button, I want that the animation still runs to reach 360 degree and then stop. The animation code is like below:

CABasicAnimation *anim2 = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
anim2.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
anim2.fromValue = [NSNumber numberWithFloat:0];
anim2.toValue = [NSNumber numberWithFloat:-((360*M_PI)/180)];
anim2.repeatCount = HUGE_VALF;
anim2.duration = 10;
[self.imgBtn.layer addAnimation:anim2 forKey:@"transform"];

Thanks!


Solution

  • While you can get the animation from the layer using animationForKey:, you cannot modify the animation that way. As the documentation explains it:

    Discussion

    Attempting to modify any properties of the returned object will result in undefined behavior.

    What you instead have to do

    You have to remove the infinite animation and add another animation that makes the final end animation.

    1. Use the presentation layer to determine the current rotation of your layer.
    2. Remove the infinite animation
    3. Add a new animation from the value you got from the presentation layer to the end state.

    How to get the value from the presentation layer.

    During animation your model doesn't change (when using Core Animation). Instead what you see on screen is the layers presentation layer. You can get then read the current value from the presentation layer just as if it was any other layer. In your case you could get the rotation using [myLayer valueForKey:@"transform.rotation"];