重复重放时,iOS动画不会重置

时间:2017-05-24 06:43:17

标签: ios animation uiview

我有一个非常简单的动画块,它执行以下动画:

  

enter image description here
  (如果动画没有播放,则点击图像)

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点。相反,我得到这种行为:

  

enter image description here
  (如果动画没有播放,则点击图像)

它显然已经超过30分。 (接近120分。)

为什么会发生这种情况,我怎样才能重置"适当的动画,以便它最多只能旅行30点?

我尝试过没有用的事情

  • 使用options: UIViewAnimationOptions.beginFromCurrentState。它的行为完全相同。
  • 不是直接执行动画,而是使用dispatch_after在几毫秒后完成。同样的行为。
  • "Canceling" the previous animation使用0秒动画将常量更改为0,然后调用superview!.layoutIfNeeded

其他说明:

  • 如果不改变位置,我通过约束改变高度,我得到类似的奇怪行为。例如。如果我把它设置为从30点到15点,当反复按下按钮时,视图显然会长到120点左右。
  • 即使我没有使用约束,而是我将transformCGAffineTransform.identity设为CGAffineTransform(scaleX: 0.5, y: 0.5),我也会遇到相同的行为。 120分。
  • 如果我尝试使用完全不同的动画属性backgroundColor = UIColor(white: 0, alpha: 0.5)backgroundColor = UIColor(white: 0, alpha: 0),那么我会得到正确的行为(即每次点击按钮时,颜色最多会重置为0.5灰色它永远不会变黑。

2 个答案:

答案 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)

到目前为止,我找到的 only 解决方案是重新创建视图,而不是尝试重置现有视图。

这给了我正在寻找的确切行为:

  

enter image description here
  (如果动画没有播放,则点击图像)

很遗憾,你需要删除旧视图并创建一个新视图,但这是我找到的唯一解决方法。