简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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