xcode 停止 UIView 动画

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11092035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 00:37:48  来源:igfitidea点击:

Stop an UIView Animation

objective-ciosxcodeuibuttonuiviewanimation

提问by alexclp

Possible Duplicate:
Cancel a UIView animation?

可能的重复:
取消 UIView 动画?

I have the following animation and i want to stop it when i press a button. Can you please tell me how can i do it? I can't figure it out how. Thanks.

我有以下动画,我想在按下按钮时停止它。你能告诉我我该怎么做吗?我想不通怎么办 谢谢。

-(void)animationLoop:(NSString *)animationID finished:(NSNumber *)finished context:(void    *)context 
{
[UIView beginAnimations:@"Move randomly" context:nil]; 
[UIView setAnimationDuration:1]; 
// [UIView setAnimationBeginsFromCurrentState:NO];


CGFloat x = (CGFloat) (arc4random() % (int) self.bounds.size.width); 
CGFloat y = (CGFloat) (arc4random() % (int) self.bounds.size.height); 

CGPoint squarePostion = CGPointMake(x, y); 
strechView.center = squarePostion; 

[UIView setAnimationDelegate:self]; 
[UIView setAnimationDidStopSelector:@selector(animationLoop:finished:context:)];

[UIView commitAnimations];

} 

回答by gdavis

Try this:

尝试这个:

[myView.layer removeAllAnimations];

and be sure to import the Quartz framework as well:

并确保导入 Quartz 框架:

#import <QuartzCore/QuartzCore.h>

Animations are applied using CoreAnimation in the QuartzCore framework, even the UIView animation methods. Just target the view's layer that you want to stop animating, and remove its animations.

使用 QuartzCore 框架中的 CoreAnimation 应用动画,甚至是 UIView 动画方法。只需定位要停止动画的视图层,并删除其动画。

回答by pasawaya

You could do this:

你可以这样做:

[self.view.layer removeAnimationForKey:@"Move randomly"];

This is more effective than calling [self.view.layer removeAllAnimations]because this can potentially remove other animations that you would want to keep.

这比调用更有效,[self.view.layer removeAllAnimations]因为这可能会删除您想要保留的其他动画。

回答by folex

You can just change the object/property that currently animated. It will stop animation.

您可以更改当前动画的对象/属性。它会停止动画。

回答by TedCheng

I suggest you use NSTimer.

我建议你使用 NSTimer。

NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(yourAnimation) userInfo:nil repeats:YES];

- (void)responseToButton:(UIButton *) _button {
    //when you want to stop the animation
    [myTimer invalidate];
}

- (void)yourAnimation {
      // move the view to a random point
}

Besides, you can set the NSTimer works on another thread so that the main thread can response when you press even your TimeInterval value is very small

此外,您可以将 NSTimer 设置在另一个线程上工作,这样即使您的 TimeInterval 值很小,主线程也可以响应