Home > Mobile >  How do I reset a circular progress bar in Swift?
How do I reset a circular progress bar in Swift?

Time:10-05

I have created a circular progress bar in Swift. I can start, pause and resume the animation, but I need to be able to reset the animation with a button tap.

Here is the code I am using to start, pause and resume the animation. What additional steps are necessary to reset it?

func startAnimation() {
    let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")
    basicAnimation.toValue = 1
    basicAnimation.duration = seconds
    basicAnimation.fillMode = CAMediaTimingFillMode.forwards
    basicAnimation.isRemovedOnCompletion = false
    shapeLayer.add(basicAnimation, forKey: "basicAnime")
}

func pauseLayer(layer: CALayer){
    let pausedTime : CFTimeInterval = layer.convertTime(CACurrentMediaTime(), from: nil)
    layer.speed = 0.0
    layer.timeOffset = pausedTime
}

func resumeAnimation(layer: CALayer){
    let pausedTime = layer.timeOffset
    layer.speed = 1.0
    layer.timeOffset = 0.0
    layer.beginTime = 0.0
    let timeSincePause = layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
    layer.beginTime = timeSincePause
}

func resetAnimation() {
    timer.invalidate()
    
    // next steps
}

CodePudding user response:

One possible solution is to simply remove the previous added animations

See CALayer#removeAllAnimations() and CALayer#removeAnimation(forKey:) for more details

  • Related