平移手势识别器:松开平移手势后,触摸位置崩溃



我正在使用平移手势识别器,我需要检测初始触摸点才能采取行动。我正在使用以下代码;

@IBAction func panDetected(sender: UIPanGestureRecognizer) {
    let touchPoint = sender.locationOfTouch(0, inView: nil)
    println(touchPoint.x)
}

这些功能在我移动手指时打印触摸点。但是,一旦我将手指从屏幕上抬起,它就会崩溃。这是崩溃消息;

Terminating app due to uncaught exception 'NSRangeException', reason: '-[UIPanGestureRecognizer locationOfTouch:inView:]: index (0) beyond bounds (0).'

我已经尝试了按照这篇文章的建议设置最小和最大触摸限制;在iOS中获取视图中的触摸位置时,PAN手势崩溃

可能是什么问题?

您遇到的问题是,一旦手势结束,它就不再有任何触摸,因此在索引 0 处不再有触摸可供检索。您可能只想使用 locationInView 方法:

let touchPoint = sender.locationInView(sender.view)

(这会对视图使用sender.view而不是nil,因为在手势识别器添加到的视图的坐标空间中获取触摸位置通常比在窗口的坐标空间中获取触摸位置更有用)

最新更新