Search code examples
swiftlocationtouchesuilongpressgesturerecogni

How do you get the location of touches for a UILongPressGestureRecognizer when the number of required touches is more than one in swift?


I would like to get the location of multiple multiple touches from a UILongPressGuestureRecognizer where the number of required touches is more than one. I know that I can do the following to get the location when one finger is used.

let twoFingerLongPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(twoFingerLongPressChordTouchView(gesture:)))
twoFingerLongPressGesture.numberOfTouchesRequired = 2
twoFingerLongPressGesture.minimumPressDuration = 0.02
self.addGestureRecognizer(twoFingerLongPressGesture)
@objc func twoFingerLongPressAction(gesture: UILongPressGestureRecognizer) {
    let location = gesture.location(in: self)
}

I also know that I can iterate through touches in the touches began callback however I am trying to make use of a specific behavior in UILongPressGestureRecognizer. Thanks in advance for any help or advice!!!


Solution

  • You can use location(ofTouch:in:) in conjunction with numberOfTouches:

    let touchPoints = (0..<twoFingerLongPressGesture.numberOfTouches).map {
        twoFingerLongPressGesture.location(ofTouch: $0, in: self)
    }
    

    This gets you all the touched points in an array of CGPoints.