swift - Swift:你如何使用 UIPanGestureRecognizer 获得每次触摸的速度?
问题描述
我想使用方法来获取每次触摸的速度,UIPanGestureRecognizer
就像您可以使用该方法对触摸位置进行的操作一样location(ofTouch: Int, in: UIView)
。但是,当我使用方法velocity(in: view)
时,它只返回触摸速度之一。我尝试更改maximumNumberOfTouches
属性,但没有成功。
有什么办法可以做到这一点?
解决方案
好的,所以我通过创建一个被调用的二维数组CGPoint
和touchLocations
另一个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 速度做同样的事情)
我知道这种方法不是很准确,但是对于我的目的来说已经足够了。
推荐阅读
- excel - 在某些单元格中循环的宏
- amazon-web-services - 使用 AWS_IAM 向 AWS WebSocket API 网关授权请求
- wso2 - 更改 WSO2 IS 5.9.0 中用户名的正则表达式限制后,Token Introspect API 不起作用?
- python-3.x - 如果函数不在模块级别,如何向 Dask 提交函数?
- laravel - 将 Northwind 数据库导入 laravel
- python - 如何复制和操作字典?
- python - 在 docker 容器中运行 tensorflow 时出错
- performance - 如何明确诊断 AIX PowerPC 上的“加载命中存储”
- javascript - 将函数更改为也适用于负值?
- javascript - Vue 组件到 Nuxt 组件