我正试图通过屏幕触摸来控制动画
当我触摸屏幕时,视图的alpha值为0
但是如果alpha在更改为0时再次接触到
然后alpha再转1次(中断动画使alpha值为0)
所以我写
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()
}
}
}但是只有在动画块完成后才调用touchesBegan。
我如何解决这个问题?
发布于 2018-05-11 08:16:49
这里有两件事你需要知道:
isUserInteractionEnabled和isInterruptible之后,不需要将它们设置为true,因为它们的默认值是true。stopAnimation后,UIViewPropertyAnimator将变得无效,您无法调用startAnimation使其再次工作。因此,您需要在停止showAnimation和hideAnimation之后重新初始化它们。要解决问题,请尝试下面的代码。
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()
}
}
}https://stackoverflow.com/questions/50287405
复制相似问题