简体   繁体   English

无休止地制作动画循环,直到我在 Swift iOS 中按下按钮。 如何?

[英]Make an animation loop endlessly until I press a button in Swift iOS. How?

Here's my code for the animation:这是我的动画代码:

UIView.animateWithDuration(3, 
  animations: {self.redBar.center = CGPointMake(self.redBar.center.x + 600, self.redBar.center.y + 600)},
  completion: nil)

I want to make it loop until I press a button.我想让它循环直到我按下一个按钮。 How?如何?

Put the animation code inside of it's own function.将动画代码放在它自己的函数中。 Call that function in the completion block of the animation unless your button has been pressed.除非您的按钮被按下,否则在动画的完成块中调用该函数。

When your button is pressed, set a boolean flag that keeps your animation from running again, then use this to cancel the animation that's in progress.当你的按钮被按下时,设置一个布尔标志来阻止你的动画再次运行,然后使用来取消正在进行的动画。

A nice solution here is to call your animation through a function accessed by a timer.一个不错的解决方案是通过计时器访问的函数调用动画。

Here's a simple example of employing a timer: How can I make a countdown with NSTimer?这是一个使用计时器的简单示例: 如何使用 NSTimer 进行倒计时?

Would probably be easiest to assign a boolean to stop the animation on button press.分配一个布尔值来在按钮按下时停止动画可能是最简单的。 Assuming timer repeats was set to true (on declaration), now just call timer.invalidate() and your timer will no longer repeat calls to your animation.假设 timer repeats 设置为 true(在声明时),现在只需调用 timer.invalidate() 并且您的计时器将不再重复调用您的动画。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM