如何在需要时停止UIViewanimation?

我有这个代码:

-(void)animationLoop{ CGPoint oldPoint = CGPointMake(myCircleUIView.frame.origin.x, myCircleUIView.frame.origin.y); [UIView animateWithDuration:1.0 animations: ^{ myCircleUIView.frame = CGRectMake(myCircleUIView.frame.origin.x + [self randomFloatingGenerator], myCircleUIView.frame.origin.y + [self randomFloatingGenerator], myCircleUIView.frame.size.width, myCircleUIView.frame.size.height); } completion: ^(BOOL finished) { [UIView animateWithDuration:1.0 animations:^{ myCircleUIView.frame = CGRectMake(oldPoint.x, oldPoint.y, myCircleUIView.frame.size.width, myCircleUIView.frame.size.height);} completion: ^(BOOL finished) {[self animationLoop];}]; }]; } 

但是我试图停止与它交互的animation,但[myCircleUIView.layer removeAllAnimations]; 会不会做这个工作,有什么build议吗?

当您停止使用CALayer's -removeAllAnimations完成callbackanimation时, finished == NO 。 所以改变你的animation代码是这样的:

 - (void)animationLoop { __weak id weakSelf = self; CGPoint oldPoint = CGPointMake(myCircleUIView.frame.origin.x, myCircleUIView.frame.origin.y); [UIView animateWithDuration:1.0 animations:^{ myCircleUIView.frame = CGRectMake(myCircleUIView.frame.origin.x + [weakSelf randomFloatingGenerator], myCircleUIView.frame.origin.y + [weakSelf randomFloatingGenerator], myCircleUIView.frame.size.width, myCircleUIView.frame.size.height); } completion:^(BOOL finished) { if (!finished) return; [UIView animateWithDuration:1.0 animations:^{ myCircleUIView.frame = CGRectMake(oldPoint.x, oldPoint.y, myCircleUIView.frame.size.width, myCircleUIView.frame.size.height); } completion:^(BOOL finished) { if (!finished) return; [weakSelf animationLoop]; }]; }]; } 

我还build议,如果因为可能的retain cycle而不真正需要,那么不要将self强引用传递给复制到堆的块。

在循环中添加bool,并在需要停止animation时将其设置为false,如下面的代码所示…

 BOOL IsAnimationContinue=true; -(void)animationLoop{ CGPoint oldPoint = CGPointMake(myCircleUIView.frame.origin.x, myCircleUIView.frame.origin.y); [UIView animateWithDuration:1.0 animations: ^{ if(IsAnimationContinue) { myCircleUIView.frame = CGRectMake(myCircleUIView.frame.origin.x + [self randomFloatingGenerator], myCircleUIView.frame.origin.y + [self randomFloatingGenerator], myCircleUIView.frame.size.width, myCircleUIView.frame.size.height); }} completion:^(BOOL finished) { [UIView animateWithDuration:1.0 animations:^{ if(IsAnimationContinue) { myCircleUIView.frame = CGRectMake(oldPoint.x, oldPoint.y, myCircleUIView.frame.size.width, myCircleUIView.frame.size.height); }} completion: ^(BOOL finished) {[self animationLoop];}]; 

}]; }

刚刚设置

 IsAnimationContinue=False 

停止animation