Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pause and resume constraint animation using UIViewPropertyAnimator

Tags:

ios

swift

I have a UIImageView that stretches the width of the screen whose trailing and leading ends I'm animating to meet in the middle of the screen. The time it takes is in relation to a timer.

I have a start button that also functions as a pause button. I can get the animation to start initially and pause without problems, but getting it to resume again from where it left off (or even at all) is where I'm having trouble.

@IBAction func startBtnPressed(_ sender: AnyObject) {
    if isStartBtnPressed == true {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(decreaseTime), userInfo: nil, repeats: true)
        isStartBtnPressed = false
        self.prepareTimeTrailing.constant = screenSize / 2
        self.prepareTimeLeading.constant = screenSize / 2
        animator = UIViewPropertyAnimator(duration: TimeInterval(timeSec), curve: .linear) {
            self.view.layoutIfNeeded()
        }
        animator.startAnimation()
    } else {
        timer.invalidate()
        isStartBtnPressed = true
        animator.pauseAnimation()
    }
}

I tried adding the piece of code below, but it didn't make a difference.

var animationTiming = UICubicTimingParameters.init(animationCurve: .linear)

animator.continueAnimation(withTimingParameters: animationTiming, durationFactor: 1.0) 
         UIView.animate(withDuration: TimeInterval(Float(timeSec)), delay: 0.0, options: [.curveLinear, .allowUserInteraction, .beginFromCurrentState], animations: {
            self.view.layoutIfNeeded()
        }, completion: nil)

Hope someone can shed some light on what I need to do to make it work.

Thanks in advance.

like image 361
Mathias Jepsen Avatar asked Sep 18 '25 17:09

Mathias Jepsen


1 Answers

I think the problem is the you create new animation when try to resume it. You need to perform startAnimation() with out create new animation class. I think you need to use some think like this:

@IBAction func startBtnPressed(_ sender: AnyObject) {
    if animator == nil{
        self.prepareTimeTrailing.constant = screenSize / 2
        self.prepareTimeLeading.constant = screenSize / 2
        animator = UIViewPropertyAnimator(duration: TimeInterval(timeSec), curve: .linear) {
            self.view.layoutIfNeeded()
    }
    if isStartBtnPressed == true {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(decreaseTime), userInfo: nil, repeats: true)
        isStartBtnPressed = false

        animator.startAnimation()
    } else {
        timer.invalidate()
        isStartBtnPressed = true
        animator.pauseAnimation()
    }
}
like image 81
Sergey Avatar answered Sep 21 '25 08:09

Sergey