Crashalot Crashalot - 3 months ago 45
Swift Question

iOS: recognize pinch gestures but not two finger pans?

The goal is to only let pinch gestures get recognized if a two-finger pan is not in process.

This code allows both pinch gestures and two-finger pan gestures, but they occur at the same time. This was based off this answer to use the

gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer: UIGestureRecognizer)
function.

// Handle two-finger pans
let twoFingerPanRecognizer = UIPanGestureRecognizer(target: self, action: #selector(sceneViewPannedTwoFingers))
twoFingerPanRecognizer.minimumNumberOfTouches = 2
twoFingerPanRecognizer.maximumNumberOfTouches = 2
twoFingerPanRecognizer.delegate = self
sceneView.addGestureRecognizer(twoFingerPanRecognizer)

// Handle pinches
let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(sceneViewPinched))
pinchGesture.delegate = self
sceneView.addGestureRecognizer(pinchGesture)

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer is UIPinchGestureRecognizer {
return false
} else {
return true
}
}


This code allows two-finger pans, but pinches do not occur at all.

// Handle two-finger pans
let twoFingerPanRecognizer = UIPanGestureRecognizer(target: self, action: #selector(sceneViewPannedTwoFingers))
twoFingerPanRecognizer.minimumNumberOfTouches = 2
twoFingerPanRecognizer.maximumNumberOfTouches = 2
twoFingerPanRecognizer.delegate = self
sceneView.addGestureRecognizer(twoFingerPanRecognizer)

// Handle taps
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(sceneViewTapped))
sceneView.addGestureRecognizer(tapRecognizer)

// Handle pinches
let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(sceneViewPinched))
pinchGesture.delegate = self
pinchGesture.requireGestureRecognizerToFail(twoFingerPanRecognizer)
sceneView.addGestureRecognizer(pinchGesture)

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}

Answer

Have you try like this

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    if ((gestureRecognizer is UIPinchGestureRecognizer || gestureRecognizer is UIPanGestureRecognizer)
         && (otherGestureRecognizer is UIPinchGestureRecognizer || otherGestureRecognizer is UIPanGestureRecognizer))  {
        return false
    }
    return true
}