I have a UIProgressView which must be be updated while the user holds a button. For a smooth animation I opted to use UIView.animateWithDuration instead of a Timer to update the progress.
What I expect to achieve is: the progress increases while the user holds a button, reaching 100% in 30 seconds (and then stops). If the user releases the button before the time ends, the progress bar just stops in the current progress. If the user then holds the button again, the progress resets to zero and the same process stars all over again.
Problem is I can't cancel the animation once the user releases the button. I tried to use progressView.layer.removeAllAnimation() but didn't work too.
Bellow is my code:
@IBAction func holdValueChanged(_ sender: CustomButton) {
if sender.isPressed {
progressView.progress = 1.0
UIView.animate(withDuration: 30.0, delay: 0.0, options: UIViewAnimationOptions.curveLinear, animations: {
self.progressView.layoutIfNeeded()
}, completion: { (finished) in
print("Ended progress animation")
})
}
else {
// stop progress animation
progressView.layer.removeAllAnimations()
}
}