Stop an auto-reverse / infinite-repeat UIView animation with a BOOL / completion block

Luke picture Luke · Dec 21, 2012 · Viewed 22.7k times · Source

I'm setting up the following UIView animateWithDuration: method, with the intention of setting my animationOn BOOL elsewhere in the program to cancel that infinite looped repeat. I was under the impression that the completion block would be called each time a cycle of the animation ends, but this doesn't appear to be the case.

Is the completion block ever called in a repeating animation? And if not, is there another way I can stop this animation from outside this method?

- (void) animateFirst: (UIButton *) button
{
    button.transform = CGAffineTransformMakeScale(1.1, 1.1);
    [UIView animateWithDuration: 0.4
                          delay: 0.0
                        options: UIViewAnimationOptionCurveEaseOut | UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat
                     animations: ^{
                         button.transform = CGAffineTransformIdentity;
                     } completion: ^(BOOL finished){
                         if (!animationOn) {
                             [UIView setAnimationRepeatCount: 0];
                         }
    }];
}

Answer

Tom van Zummeren picture Tom van Zummeren · Dec 21, 2012

The completion block will only get called when the animation is interrupted. For example it gets called when the app goes in the background and comes back to the foreground again (via multitasking). In that case the animation is stopped. You should restart the animation when that happens.

To stop the animation you can remove it from the view's layer:

[button.layer removeAllAnimations];