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:
isUserInteractionEnabled
and isInterruptible
to true after initializing UIViewPropertyAnimator
because their default values are true.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()
}
}
}