简体   繁体   中英

Pan Gesture Recognizer: Location of touch crashes once the pan gesture is released

I am using pan gesture recognizer and I need to detect the initial touch point in order to take action. I am using the following code;

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

The functions prints the touch points as I move my finger. However it crashes once I lift my finger from the screen. Here is the crash message;

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

I have already experimented with setting minimum and maximum touch limits as this post suggests; PAN Gesture is crashing while taking the location of touch in view in iOS

What can be the problem?

The issue you're hitting is that once the gesture ends it no longer has any touches, so there's no longer a touch at index 0 to retrieve. You probably just want to use the locationInView method:

let touchPoint = sender.locationInView(sender.view)

(this uses sender.view rather than nil for the view, since it's generally more useful to get the touch position in the coordinate space of the view that the gesture recognizer's added to than in the coordinate space of the window)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM