6
votes

I have defined longPress and Pan gesture recognizers at viewController class level as below:

var touch = UILongPressGestureRecognizer()
var pan = UIPanGestureRecognizer()

Then I create a simple UIView:

let qBox = UIView()
qBox.frame = CGRect(x: 100, y: 200, width: 50, height: 50)
self.view.addSubview(qBox)

Then I configure and add my recognizers:

touch.addTarget(self, action: "ourTouched:")
touch.minimumPressDuration = 0
touch.numberOfTouchesRequired = 1
touch.numberOfTapsRequired = 0
qBox.addGestureRecognizer(touch)

pan.addTarget(self, action:"pan:")
pan.maximumNumberOfTouches = 1
pan.minimumNumberOfTouches = 1
self.view.addGestureRecognizer(pan)

Now, when I touch the qBox UIView, it triggers "ourTouched" method but if I keep holding and then start panning, it will not drag the qBox UIView. I have tried adding below line in my "ourTouched" function to remove the long press recognizer as soon as user touches the qBox UIView:

qBox.removeGestureRecognizer(touch)

But still, on first touch and drag, only long press method is called. I have to let go and then start again to pan. What am I missing?

1

1 Answers

11
votes

Add a UIGestureRecognizerDelegate to your recognizers and have it return YES on shouldRecognizeSimultaneously.

{
  // setup ...
  touch.delegate = self
}

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
  return (gestureRecognizer == touch && otherGestureRecognizer == pan)
}

Update: Swift 4 or later

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return (gestureRecognizer == touch && otherGestureRecognizer == pan)
 }