0
votes

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?

1

1 Answers

9
votes

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)