iosswiftuikitcalayeruiprogressview

UIProgressView doesn't restart if the animation hasn't finished


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


Solution

  • You need to

    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)
        }