Nayan Chauhan
Nayan Chauhan

Reputation: 542

Disable multiple long-press gestures simultaneously

I have a UIView and i have multiple UIImageView's as its subview. I have added UILongPressGestureRecognizer to each of these subviews. I handle this gesture in a method where i perform some animation on the sender UIImageView.

If I long press two ImageView's at a time, the animation gets disrupted.

Is there any way I can disable multiple long press gestures simultaneously? i.e allow only one UIImageView to detect LongPress gesture.

Upvotes: 2

Views: 2615

Answers (2)

OhadM
OhadM

Reputation: 4801

We can also address the issue if we are using TableViewController and we want UILongPressGestureRecognizer to operate on only one cell simultaneously.

First we will need to define a static var in the CustomCell:

static var isLongPressInProgress = false

and then in the gestureRecognizerShouldBegin which states if we can use the gesture:

override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {        
    if let _ = gestureRecognizer as? UILongPressGestureRecognizer {
        if CustomCell.isLongPressInProgress == true {
          return false
        }
      return true
     }
  return false
 }

You will set the var isLongPressInProgress in the case .Began: to true and at the case .Ended: to false

Upvotes: 2

Evgeny Shurakov
Evgeny Shurakov

Reputation: 6082

You have actually several ways to solve your problem:

Set exclusiveTouch to YES for all your image views. It will block the delivery of touch events to other views in the same window.

Or you can set flag to ignore other recognizers when one of your recognizers move to Begin state.

Or you can disable gesture recognizers (UIGestureRecognizer has enabled property) except current one in your delegate method and enable all of them again when gesture finishes.

Upvotes: 7

Related Questions