-2

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?

αƞjiβ
  • 3,056
  • 14
  • 58
  • 95
Pedro Cabaço
  • 123
  • 12
  • Does this answer your question? [UIView.animateWithDuration swift loop animation](https://stackoverflow.com/questions/27660540/uiview-animatewithduration-swift-loop-animation) – shadow of arman Mar 15 '21 at 16:03

2 Answers2

1

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.

Community
  • 1
  • 1
JordanC
  • 1,303
  • 12
  • 28
0

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.