首页 > 解决方案 > Swift:你如何使用 UIPanGestureRecognizer 获得每次触摸的速度?

问题描述

我想使用方法来获取每次触摸的速度,UIPanGestureRecognizer就像您可以使用该方法对触摸位置进行的操作一样location(ofTouch: Int, in: UIView)。但是,当我使用方法velocity(in: view)时,它只返回触摸速度之一。我尝试更改maximumNumberOfTouches属性,但没有成功。

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

标签: swiftuipangesturerecognizer

解决方案


好的,所以我通过创建一个被调用的二维数组CGPointtouchLocations另一个CGPoint被调用的数组来解决这个问题touchVelocities。在循环所有触摸的 for 循环中,我添加了

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

CGPoint为每个触摸分配一个新的(touchNumber是触摸的索引,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 速度做同样的事情)

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


推荐阅读