0

我正在尝试通过屏幕触摸来控制动画

当我触摸屏幕时,视图的 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 仅在动画块完成后调用

我怎么解决这个问题

4

1 回答 1

2

这里有两件事你需要知道:

  • 初始化后不需要将isUserInteractionEnabledand设置为 true,因为它们的默认值为 true。isInterruptibleUIViewPropertyAnimator
  • 调用后stopAnimationUIViewPropertyAnimator将失效,无法再调用startAnimation。所以你需要重新初始化showAnimationhideAnimation停止它们。

要解决问题,请尝试下面的代码。

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()
    }
  }
}
于 2018-05-11T08:16:49.967 回答