简体   繁体   中英

interrupt animation by touch using UIViewPropertyAnimator

I'm trying to control the animation by screen touch

when i touches screen then view's alpha goes 0

but if touches again while alpha is changing to 0

then alpha goes 1 again (interrupt animation which make alpha value 0)

so i write

class MainViewController: UIViewController {

var showAnimation:UIViewPropertyAnimator!
var hideAnimation:UIViewPropertyAnimator!
var isHiding:Bool = false
override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = .blue

    showAnimation = UIViewPropertyAnimator(duration: 2, curve: .easeInOut, animations: {
        self.view.alpha = 1
    })
    hideAnimation = UIViewPropertyAnimator(duration: 2, curve: .easeInOut, animations: {
        self.view.alpha = 0
    })
    showAnimation.isUserInteractionEnabled = true
    showAnimation.isInterruptible = true
    hideAnimation.isUserInteractionEnabled = true
    hideAnimation.isInterruptible = true
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    isHiding = !isHiding
    if self.isHiding {
        self.hideAnimation.startAnimation()
        self.showAnimation.stopAnimation(true)
    }else{
        self.hideAnimation.stopAnimation(true)
        self.showAnimation.startAnimation()
    }
}
}

but touchesBegan called only after animation blocks are finished

how can i solve this problem

There are 2 things you need to know here:

  • You don't need to set isUserInteractionEnabled and isInterruptible to true after initializing UIViewPropertyAnimator because their default values are true.
  • After calling stopAnimation , UIViewPropertyAnimator will become invalid and you can't call startAnimation to make it work again. So you need to reinitialize showAnimation and hideAnimation after stop them.

To resolve problem, try my code below.

class MainViewController: UIViewController {

  var showAnimation:UIViewPropertyAnimator!
  var hideAnimation:UIViewPropertyAnimator!
  var isHiding:Bool = false
  override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = .blue
  }

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    isHiding = !isHiding
    if self.isHiding {
      self.showAnimation?.stopAnimation(true)

      self.hideAnimation = UIViewPropertyAnimator(duration: 2, curve: .easeInOut, animations: {
        self.view.alpha = 0.1
      })
      self.hideAnimation.startAnimation()
    }else{
      self.hideAnimation?.stopAnimation(true)

      self.showAnimation = UIViewPropertyAnimator(duration: 2, curve: .easeInOut, animations: {
        self.view.alpha = 1
      })
      self.showAnimation.startAnimation()
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM