Search code examples
iosobjective-ccore-animationuiviewanimationcabasicanimation

CABasicAnimation stop animation on completion - iOS


I have an iOS app which is using a CABasicAnimation on repeat:

    CABasicAnimation *fadeAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeAnim.fromValue = [NSNumber numberWithFloat:1.0];
    fadeAnim.toValue = [NSNumber numberWithFloat:0.2];
    fadeAnim.duration = 1.0;
    fadeAnim.autoreverses = YES;
    fadeAnim.repeatCount = INFINITY;
    [colourbutton.titleLabel.layer addAnimation:fadeAnim forKey:@"opacity"];

I have a button which when pressed is meant to stop the animation.

-(IBAction)stopAnim {
    [colourbutton.titleLabel.layer removeAllAnimations];
}

It works fine but one thing I am noticing is that is stops the animation suddenly, it doesn't let the animation finish. So how can I get it to finish the current animation and then stop. (Or in other words how can I get it to removeAllAnimations....withAnimation?).

On a side note, do I need to include CoreAnimation framework for this to work. So far the animation is running and I havn't imported the CoreAnimation framework.

Thanks, Dan.


Solution

  • Just add another animation and after that remove the first one like this:

        CABasicAnimation *endAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
        endAnimation.fromValue = @(((CALayer *)colourbutton.titleLabel.layer.presentationLayer).opacity);
        endAnimation.toValue = @(1);
        endAnimation.duration = 1.0;
        [colourbutton.titleLabel.layer addAnimation:endAnimation forKey:@"end"];
        [colourbutton.titleLabel.layer removeAnimationForKey:@"opacity"];
    

    The key here is to use the presentation layer to get the current state. Don't forget to set the actual end state of the layer, because the animation will be removed on completion.