0

I'm doing a workout app and I have a UIProgressView that gets filled with animation while the exercice is happening. At the end of it, it gets restarted to 0 and filled again with the next exercice of the workout. This works well except when the user presses "Next" without the animations being finished.

In that case, the animation goes to 0 as expected but then it doesn't start again until 4-5 seconds after.

This is how my code looks:

self.exerciceView.progressView.setProgress(0.0, animated: false)
self.view.layoutIfNeeded()
        
startTimer()
        
UIView.animate(withDuration: TimeInterval(seconds)) {
    self.exerciceView.progressView.setProgress(1.0, animated: true)
}
self.view.layoutIfNeeded()

Any idea of what's happenings? I've been stuck with this bug for a week now.

Thank you!

enter image description here

Joan Cardona
  • 3,463
  • 2
  • 25
  • 43
  • You probably need to use `removeAllAnimations` -- see https://stackoverflow.com/questions/9569943/how-to-cancel-uiview-block-based-animation – jnpdx Jul 26 '21 at 17:09

1 Answers1

1

You need to

  • remove the current animations
  • reset the progress to 0.0
  • and force the progressView to layout:

This should do it:

    // remove animations from all layers of progressView
    if let layers = exerciceView.progressView.layer.sublayers {
        layers.forEach { layer in
            layer.removeAllAnimations()
        }
    }
    // reset to 0.0
    self.exerciceView.progressView.setProgress(0.0, animated: false)
    // force layout
    self.exerciceView.progressView.setNeedsLayout()
    self.exerciceView.progressView.layoutIfNeeded()

    // animate progressView
    UIView.animate(withDuration: TimeInterval(seconds)) {
        self.exerciceView.progressView.setProgress(1.0, animated: true)
    }
DonMag
  • 69,424
  • 5
  • 50
  • 86