停止基于块的动画链的最佳方法是什么?

时间:2011-11-18 22:59:34

标签: iphone objective-c ios ipad ios4

假设有一系列基于块的动画,如下所示:

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

阻止这种动画的最佳方法是什么?只需致电

[view.layer removeAllAnimations];

是不够的,因为它只停止当前正在执行的动画块,其余的将按顺序执行。

2 个答案:

答案 0 :(得分:11)

您可以参考传入完成块的finished BOOL。在您拨打removeAllAnimations

的情况下,它将为NO

答案 1 :(得分:8)

我使用以下方法:

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消息立即停止动画块并调用其完成块。在那里检查动画标志并停止链。

有更好的方法吗?