我有一个非常简单的动画块,它执行以下动画:
func didTapButton() {
// reset the animation to 0
centerYConstraint.constant = 0
superview!.layoutIfNeeded()
UIView.animate(
withDuration: 1,
animations: {
// animate the view downwards 30 points
self.centerYConstraint.constant = 30
self.superview!.layoutIfNeeded()
})
}
当我独自播放动画时,一切都很棒。它重置为位置0,然后动画30点。
问题是当用户快速点击按钮多次时(即在正在进行的动画中间)。每次用户点击按钮时,我都希望它重置为0位置,然后向下动画30点。相反,我得到这种行为:
它显然已经超过30分。 (接近120分。)
为什么会发生这种情况,我怎样才能重置"适当的动画,以便它最多只能旅行30点?
我尝试过没有用的事情:
options: UIViewAnimationOptions.beginFromCurrentState
。它的行为完全相同。0
秒动画将常量更改为0
,然后调用superview!.layoutIfNeeded
。其他说明:
transform
从CGAffineTransform.identity
设为CGAffineTransform(scaleX: 0.5, y: 0.5)
,我也会遇到相同的行为。 120分。backgroundColor = UIColor(white: 0, alpha: 0.5)
到backgroundColor = UIColor(white: 0, alpha: 0)
,那么我会得到正确的行为(即每次点击按钮时,颜色最多会重置为0.5
灰色它永远不会变黑。答案 0 :(得分:3)
我可以重现你描述的行为。但是,如果我在正在移动的视图层上调用removeAllAnimations()
,问题就会消失。
@IBAction func didTapButton(_ sender: Any) {
animatedView.layer.removeAllAnimations()
centerYConstraint.constant = 0
view.layoutIfNeeded()
centerYConstraint.constant = 30
UIView.animate(withDuration: 2) {
self.view.layoutIfNeeded()
}
}
注意,我不会从超级视图中删除动画(因为这仍然表现出您描述的行为),而不是正在移动的视图。
答案 1 :(得分:1)