如何让处理程序重复UIView animateWithDuration?

Cen*_*ion 2 iphone animation repeat uiview ios

我正在使用UIView类方法animateWithDuration来重复我的视图动画.我怎么能有一个可以用来稍后停止这个动画的处理程序?例如,重复动画在一个方法中启动,我需要稍后从另一个方法停止它.

jam*_*guy 8

假设您已创建已取消的属性,则可以执行此类操作.如注释中所述,完成块的startAnimation调用需要包含在异步调用中以避免堆栈溢出.一定要用你实际拥有的任何类型替换"id".

- (void)startAnimation {
    [UIView animateWithDuration:1.0
                          delay:0.0
                        options:UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction
                     animations:^(void) {
                         //animate
                     }
                     completion:^(BOOL finished) {
                         if(!self.canceled) {
                             __weak id weakSelf = self;
                             [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                                 [weakSelf startAnimation];
                             }];
                         }
                     }
     ];
}
Run Code Online (Sandbox Code Playgroud)

  • 这最终不会填满堆栈吗? (4认同)
  • 它将无限地导致堆栈UI对象,因为当您调用方法时,进程将再次启动并且它不是异步的. (2认同)

Cen*_*ion 8

动画的目的是重复动画图像的反弹.当不用担心手动停止它时,你只需要设置三个属性(UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat)和动画块代码来移动图像 - self.image.center = CGPointMake(self.image.center.x, self.image.center.y+25);这是动画的完整代码:

[UIView animateWithDuration:0.5 delay:0 options:( UIViewAnimationOptionCurveEaseIn | 
 UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat | 
 UIViewAnimationOptionAllowUserInteraction) animations:^{self.image.center = 
 CGPointMake(self.image.center.x, self.image.center.y+25);} completion:nil];
Run Code Online (Sandbox Code Playgroud)

而已.但如果您需要手动控制,则需要一些额外的代码.首先,根据jaminguy,你需要有一个BOOL属性用于指示循环/停止(self.playAnimationForImage)动画和清理单独的方法,动画代码将从其他地方调用.这是方法:

-(void)animateImageBounce{
 [UIView animateWithDuration:0.5 delay:0 options:( 
  UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionAutoreverse |  
  UIViewAnimationOptionAllowUserInteraction) animations:^{self.image.center = 
  CGPointMake(self.image.center.x, self.image.center.y+25);} completion:^(BOOL finished){if 
  (finished && self.playAnimationForImage){
    self.image.center = CGPointMake(self.image.center.x, self.image.center.y-25); 
    [self animateImageBounce];
  }}]; 
Run Code Online (Sandbox Code Playgroud)

这是从某种方法开始的动画调用

-(void)someMethod{
...
self.playAnimationForFingers = YES;
[self animateImageBounce];
Run Code Online (Sandbox Code Playgroud)

}

我想要注意的是,在手动控制中,您需要在执行下一次递归调用之前重置图像的center.y.