How to pause and resume UIView.animateWithDuration

前端 未结 3 1665
死守一世寂寞
死守一世寂寞 2020-12-13 07:29

I have an image, I animate it with this code, in viewDidAppear:

UIView.animateWithDuration(10.5, delay:0.0, options: [], animations:{
self.myImage.transform          


        
3条回答
  •  独厮守ぢ
    2020-12-13 08:08

    Since iOS 10 provides UIViewPropertyAnimator you can solve your problem easier.

    Declare these properties in your controller:

    var animationPaused = false
    lazy var animator: UIViewPropertyAnimator = UIViewPropertyAnimator(duration: 10.5, curve: .easeInOut, animations: {
    
        self.myImage.transform = CGAffineTransform(translationX: 0.0, y: 200)
    })
    

    Add the following code to the tap handler of myPauseButton:

    if self.animator.state == .active { // Don't start or pause the animation when it's finished
    
        self.animationPaused = !self.animationPaused
        self.animationPaused ? self.animator.pauseAnimation() : self.animator.startAnimation()
    }
    

    Start the animation in viewDidAppear(_ animated: Bool) with these lines of code:

    self.animationPaused = false
    self.animator.startAnimation()
    

提交回复
热议问题