Swift:如何通过UIPanGestureRecognizer获得每次触摸的速度?

问题描述 投票:0回答:1

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

有什么办法可以实现?

swift uipangesturerecognizer
1个回答
0
投票

[好,所以我通过创建一个名为CGPoint的2D数组touchLocations和另一个名为CGPointtouchVelocities数组来解决此问题。在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速度做相同的事情)

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

© www.soinside.com 2019 - 2024. All rights reserved.