如何取消以前的animation,当一个新的触发?

我正在写相机应用程序,并且在用户点击屏幕时显示焦点方块时遇到问题。

我的代码是(迅速):

self.focusView.center = sender.locationInView(self.cameraWrapper) self.focusView.transform = CGAffineTransformMakeScale(2, 2) self.focusView.hidden = false UIView.animateWithDuration(0.5, animations: { [unowned self] () -> Void in self.focusView.transform = CGAffineTransformIdentity }, completion: { (finished) -> Void in UIView.animateWithDuration(0.5, delay: 1.0, options: nil, animations: { () -> Void in self.focusView.alpha = 0.0 }, completion: { (finished) -> Void in self.focusView.hidden = true self.focusView.alpha = 1.0 }) }) 

但是,如果在上一个animation没有完成的时候连续点击屏幕,新旧animation会混淆,焦点视图会performanceexception,例如它会很快消失。

任何人都可以告诉我如何取消以前的animation,尤其是以前的完成块吗?

你可以通过用户方法removeAllAnimations来停止animation
用下面的代码replace你的代码

 self.focusView.center = sender.locationInView(self.cameraWrapper) self.focusView.transform = CGAffineTransformMakeScale(2, 2) self.focusView.hidden = false self.focusView.layer.removeAllAnimations() // <<==== Solution UIView.animateWithDuration(0.5, animations: { [unowned self] () -> Void in self.focusView.transform = CGAffineTransformIdentity }, completion: { (finished) -> Void in UIView.animateWithDuration(0.5, delay: 1.0, options: nil, animations: { () -> Void in self.focusView.alpha = 0.0 }, completion: { (finished) -> Void in self.focusView.hidden = true self.focusView.alpha = 1.0 }) }) 

参考: 链接
在这里输入图像说明

在我的情况下,我只需要设置值,我animation到具体的价值。

例如

  if ([indexPath isEqual:self.currentPlayerOrderIndexPath]) { [UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat | UIViewAnimationOptionCurveEaseInOut animations:^{ cell.avatarImageV.transform = CGAffineTransformMakeScale(1.15,1.15); } completion:NULL]; } else { cell.avatarImageV.transform = CGAffineTransformMakeScale(1.0, 1.0); 

在我的情况下,我使用addSubview()添加聚焦指标。

 self.view.addSubview(square) 

square是我在函数中定义的UIView。 所以当用户点击屏幕进行对焦时,此function会在子视图上添加一个正方形。 而当下一个水龙头发生时取消这个animation,我只是简单地使用removeFromSuperview()函数,当这个函数调用它从它的超级视图,这是聚焦广场这里删除视图。

 filterView.subviews.forEach({ $0.removeFromSuperview() }) 

这与上面删除animation的方法不同,但直接删除子视图。