什么是阻止一连串基于块的animation的最好方法

假设一系列基于块的animation,如下所示:

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]; }]; }]; 

什么是停止这种animation的最好方法? 只是打电话

 [view.layer removeAllAnimations]; 

是不够的,因为它只停止当前正在执行的animation块,其余的将依次执行。

你可以参考finished BOOL传递给你的完成块。 在你调用removeAllAnimations的情况下,它将是NO。

我使用以下方法:

 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]; } 

removeAllAnimations消息立即停止animation块,并调用其完成块。 在那里检查animation标志,链条停止。

有没有更好的方法来做到这一点?