UIView Animation won't Loop

I've got a view where I need the animation to repeat with a completion handler and update labels. The animation only runs once and then it doesn't repeat.
Code Block
    let sums = ["add(5, 7)", "mult(6, 20)", "div(15, 3)", "mult(2, 1)"]
    let answers = [12, 120, 5, 2]
    func sumAnimation() {
        for i in 0...sums.count-1 {
            inputLbl.text = sums[i]
            inputLbl.frame = CGRect(x: 0, y: 13, width: Int(inputLbl.frame.width), height: Int(inputLbl.frame.height)) // move to 340
            
            UIView.animate(withDuration: 3 - clockSpeed/2) {
                self.inputLbl.transform = CGAffineTransform(translationX: 700, y: 0)
            } completion: { (true) in
                self.outputLbl.text = "ansr(\(self.answers[i]))"
            } // End Completion
        } // End Loop
    } // End Func

Replies

Hi!

You may have misunderstood how 'UIView.animate' works. When you execute 'UIView.animate' with loops, the program will not wait until the end of the animation before executing the next loop, So you're actually executing four animations at the same time. That's why you can only see the last animation. You need to start executing the next animation after the previous one has finished.

The following code should solve your problem, but note that it is not necessarily the best solution. It's for helping you understand how it works.

Code Block swift
let data = [1, 2, 3, 4]
var i = 0
func doAnimations() {
  UIView.animate(withDuration: 1) {
    // make animations here
    // eg: view.frame.origin = CGPoint(x: data[i], y: data[i])
  } completion: { (isFinished) in
    i += 1
    if i >= data.count { return }
    doAnimations()
  }
}


🦁️🦁️🦁️🦁️🦁️ Hope this helps you!
Thanks, I see what you mean. What I'm trying to do is set a label, move it behind another view, make it disappear then set another label and start moving it from where the other one stopped. I do have this working with the code you gave but what would be the netter/correct approach to this? Another animation I need to do it create multiple dots in a vertical line (at different points in time) and move each along the x axis to a point then disappear. Again it pretty much works using the code above but I'm not sure how this should be done. Should I be using SpriteKit? I haven't really done much with animation before.