ios - 使用 UIViewPropertyAnimator 通过触摸中断动画

标签 ios swift touchesbegan uiviewpropertyanimator

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

当我触摸屏幕然后 View 的 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 仅在动画 block 完成后调用

我该如何解决这个问题

最佳答案

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

  • 在初始化 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()
    }
  }
}

关于ios - 使用 UIViewPropertyAnimator 通过触摸中断动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50287405/

相关文章:

ios - 获取添加了 longpressGesture 识别器的 View 坐标

ios - 使用代码和 Collection View 进行 segue

ios - 跟踪指定 UIViewController 子类的所有触摸

ios - 呈现 UIView 后触摸开始延迟

ios - iOS 应用内购买问题

ios - ld : library not found for -lstdc++. 6 - Xcode 10

swift - Xcode 全屏 pdf 生成器

iphone - 触摸开始驳回 View

javascript - 安装带有转换错误的 fuse.js 时,React-native 应用程序崩溃

ios - 来自 Tracker Network API (SWIFT) 的 JSON