我在滑动
期间成功获取了x和y起始坐标
:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let position :CGPoint = touch.locationInView(view)
startX = Int(position.x)
startY = Int(position.y)
}
}
我还需要滑动期间的 y 坐标。我已经成功地使用 UIPanGestureRecognizer
以一种非常迂回的方式做到了这一点。
必须有某种方法可以用尽可能少的行数来获取起始坐标。
有人能帮我指出正确的方向吗?
最诚挚的问候,尼克拉斯
最佳答案
您可以使用UIPanGestureRecognizer
来实现此目的。它将为您提供滑动的 x 和 y 坐标。 Apple 专门为此场景创建了此功能 - 它比 TouchMoved 更容易实现并自行跟踪所有内容。
要设置手势识别器:
let gestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePan:")
self.someDraggableView.addGestureRecognizer(gestureRecognizer)
要获取翻译(在上面设置的回调中):
func handlePan(gestureRecognizer: UIPanGestureRecognizer) {
if gestureRecognizer.state == .Began {
// When the drag is first recognized, you can get the starting coordinates here
}
if gestureRecognizer.state == .Changed {
let translation = gestureRecognizer.translationInView(self.view)
// Translation has both .x and .y values
}
}
在回调的 .Changed
部分中,每次用户在给定 View 中移动手指时都会调用您的代码。您可以从 translation.y
您可以查看更多示例here .
关于ios - 在快速平移滑动手势期间获取 y 坐标的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38666712/