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

7 iphone objective-c ipad ios4 ios

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

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];
     }];
}];
Run Code Online (Sandbox Code Playgroud)

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

[view.layer removeAllAnimations];
Run Code Online (Sandbox Code Playgroud)

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

Jes*_*sak 11

您可以参考finished传入完成块的BOOL.在你打电话的情况下,它将是NO removeAllAnimations.

  • 当你设置了UIViewAnimationOptionAllowUserInteraction选项时,Jesse你的建议是有效的. (6认同)
  • 哇,这是一个非常随意的发现.我想知道为什么这很重要. (2认同)

小智 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];
}
Run Code Online (Sandbox Code Playgroud)

removeAllAnimations消息立即停止动画块并调用其完成块.在那里检查动画标志并停止链.

有没有更好的方法呢?

  • 你没有在选项中设置`UIViewAnimationOptionAllowUserInteraction`.如何调用`stop`?用户点击/平底锅?如果是这样,那么根据你的代码不会调用`stop`.看看......无论如何,应该使用`finished`,如上所述. (3认同)