如何让动画和手势识别器协同工作?(迅速)

deg*_*mon 1 animation uigesturerecognizer ios swift

我做了一个简单的项目,带有滑动手势识别器和动画。我让我的标签移动,每 3 秒增加一次。每次滑动我都需要减少数字。我的手势识别器对象与标签绑定,即它仅适用于标签边界。当 prog 在没有动画的情况下工作时一切正常,但是当它被动画并移动时,我的手势识别器什么都不做。如何使手势识别器与动画同时工作,即在动画响应我的滑动时。需要帮忙。

`

 @IBOutlet weak var label1: UILabel!

var number : Int = 0
var timer = Timer()

@IBAction func label1SwipeRight(_ sender: UISwipeGestureRecognizer) {
    number += 1
    label1.text = String(number)
}

func animate1() {
    UIView.animate(withDuration: 4.0, delay: 0.0, options: .allowUserInteraction, animations: {
        let num1 : CGFloat = CGFloat(arc4random_uniform(667))
        let num2 : CGFloat = CGFloat(arc4random_uniform(375))
        self.label1.frame.origin.y = num1
        self.label1.frame.origin.x = num2
    }, completion: {(bool) in
        self.animate1()
        print("Animation1 completed")
    })
}

func timerExample() {
    Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)

}

@objc func updateTimer() {
    label1.text = String(Int(label1.text!)! + 1)
}`
Run Code Online (Sandbox Code Playgroud)

Dun*_*n C 5

默认情况下,当动画“飞行”时,视图对象会阻止用户交互。您需要使用“长格式”动画方法之一,并传入选项.allowUserInteraction. 像这样的东西:

UIView.animate(duration: 0.5,
  delay: 0.0,
  options: .allowUserInteraction,
  animations: {
    myView.alpha = 0.5
  })
Run Code Online (Sandbox Code Playgroud)

但是请注意,如果您正在设置动画的是视图的位置,则用户将无法在视图对象移动时点击它。这是因为随着时间的推移,位置动画并没有真正将对象从一个地方动画到另一个地方。它只是创造了这种外观。在幕后,对象实际上会在动画开始的那一刻跳到它的最终位置。

如果您需要能够在对象移动时点击/拖动/滑动对象,则必须自己完成。您要做的是在包含整个运动范围(可能是整个屏幕)的父视图上放置一个手势识别器。然后您需要使用动画视图层的表示层,从手势识别器的位置转换点的坐标坐标空间到图层的坐标空间,使用图层的hitTest方法判断点是否在图层上。

我在 Github 上有一个名为iOS-CAAnimation-group-demo 的项目,它执行类似的操作(它沿着复杂的路径对图像视图进行动画处理,您可以点击图像视图以在“飞行中”时暂停动画。

它来自几年前,所以它是用 Objective-C 编写的,但它至少应该有助于说明该技术。