Reid Brown
Reid Brown

Reputation: 13

How to make an animation repeat a certain amount of times?

For some reason when I click on the button it just does nothing and the whole app shuts down. Does anyone have any suggestions? They would be much appreciated.

var start = 1
var timer = Timer()

func test() {
    start += 1
}

@IBAction func start(_ sender: Any) {
    timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(TestViewController.test), userInfo: nil, repeats: true)

    while start <= 10 {
        UIView.animate(withDuration: 0.1, delay: 0, options: [.repeat, .autoreverse], animations: {
            self.buttonLabel.center = CGPoint(x:self.buttonLabel.center.x + 10, y:self.buttonLabel.center.y)
    }, completion: nil)
    }
}

Upvotes: 1

Views: 1259

Answers (1)

Ivan Nesterenko
Ivan Nesterenko

Reputation: 969

There is a better way to repeat animations, try UIView.setAnimationRepeatCount()

@IBAction func start(_ sender: Any) {
    UIView.animate(withDuration: 0.1, delay: 0, options: [.repeat], animations: {
        UIView.setAnimationRepeatCount(10)
        self.buttonLabel.center = CGPoint(x:self.buttonLabel.center.x + 10, y:self.buttonLabel.center.y)
    }, completion: nil)
}

Upvotes: 3

Related Questions