Swift:如何使用 UIPanGestureRecognizer 获取每次触摸的速度?

Swift: How do you get the velocity for each touches with UIPanGestureRecognizer?

我想使用 UIPanGestureRecognizer 获取每次触摸的速度,就像您可以使用方法 location(ofTouch: Int, in: UIView) 处理触摸位置一样。但是,当我使用方法 velocity(in: view) 时,它只是 returns 一种触摸速度。我尝试更改 maximumNumberOfTouches 属性 但它没有用。

有什么办法可以做到这一点吗?

好的,所以我通过创建一个名为 touchLocationsCGPoint 的二维数组和另一个名为 touchVelocitiesCGPoint 数组来解决这个问题。在遍历所有触摸的 for 循环中,我添加了

if !touchLocations.indices.contains(touchNumber) {
    touchLocations.append([CGPoint]())
}
touchLocations[touchNumber].append(sender.location(ofTouch: touchNumber, in: view))

为每个触摸分配一个新的 CGPointtouchNumber 是触摸的索引,sender 是手势识别器)。

然后我添加了

touchLocations[touchNumber] = touchLocations[touchNumber].suffix(2)

这样数组只包含最后 2 个元素。

为了获得速度,我只是做了

touchVelocities.insert(CGPoint(x: touchLocations[touchNumber].last!.x - touchLocations[touchNumber].first!.x, y: touchLocations[touchNumber].last!.y - touchLocations[touchNumber].first!.y), at: touchNumber)

(从 x 速度的第二个 x 值中减去第一个 x 值,对 y 速度做同样的事情)

我知道这种方法不是很准确,但是对于我的目的来说已经足够了。