What is the best way to stop the block animation chain

Assuming a chain of block-based animations, as shown below:

UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)]; //animation 1 [UIView animateWithDuration:2 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{ view.frame = CGRectMake(0, 100, 200, 200); } completion:^(BOOL finished){ //animation 2 [UIView animateWithDuration:2 delay:0 options: UIViewAnimationOptionRepeat |UIViewAnimationOptionAutoreverse animations:^{ [UIView setAnimationRepeatCount:1.5]; view.frame = CGRectMake(50, 100, 200, 200); } completion:^(BOOL finished){ //animation 3 [UIView animateWithDuration:2 delay:0 options:0 animations:^{ view.frame = CGRectMake(50, 0, 200, 200); } completion:nil]; }]; }]; 

What would be the best way to stop such an animation? Just calling

 [view.layer removeAllAnimations]; 

not enough, since it only stops the current executable animation block, and the rest will be executed sequentially.

+7
ios objective-c iphone ios4 ipad
Nov 18 '11 at 10:59 a.m.
source share
2 answers

You can refer to finished BOOL passed to your completion blocks. This will be NO if you called removeAllAnimations .

+11
Nov 18 2018-11-11T00:
source share

I use the following approach:

 UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)]; //set the animating flag animating = YES; //animation 1 [UIView animateWithDuration:2 delay:0 options:UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction animations:^{ view.frame = CGRectMake(0, 100, 200, 200); } completion:^(BOOL finished){ //stops the chain if(! finished) return; //animation 2 [UIView animateWithDuration:2 delay:0 options: UIViewAnimationOptionRepeat |UIViewAnimationOptionAutoreverse | UIViewAnimationOptionAllowUserInteraction animations:^{ [UIView setAnimationRepeatCount:1.5]; view.frame = CGRectMake(50, 100, 200, 200); } completion:^(BOOL finished){ //stops the chain if(! finished) return; //animation 3 [UIView animateWithDuration:2 delay:0 options:0 animations:^{ view.frame = CGRectMake(50, 0, 200, 200); } completion:nil]; }]; }]; - (void)stop { animating = NO; [view.layer removeAllAnimations]; } 

The removeAllAnimations message immediately terminates the animation block and its completion block is called. There the animation flag is checked and the chain is stopped.

Is there a better way to do this?

+8
Nov 18 2018-11-11T00:
source share



All Articles