【问题标题】:interrupt animation by touch using UIViewPropertyAnimator使用 UIViewPropertyAnimator 通过触摸中断动画
【发布时间】:2018-05-11 07:41:15
【问题描述】:

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

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

我该如何解决这个问题

【问题讨论】:

  • 你试过用UITapGestureRecognizer代替touchesBegan吗?
  • 一样!但如果不将 alpha 设置为 0,我认为我将 alpha 设置为 0.1 是可行的

标签: ios swift touchesbegan uiviewpropertyanimator


【解决方案1】:

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

  • 你不需要在初始化UIViewPropertyAnimator之后将isUserInteractionEnabledisInterruptible设置为true,因为它们的默认值是true。
  • 调用stopAnimation后,UIViewPropertyAnimator将失效,不能再调用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()
    }
  }
}

【讨论】:

  • 完美运行!!非常感谢!!我没有注意到我应该初始化动画对象
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多