Search code examples
iosuigesturerecognizergestureuitapgesturerecognizersimultaneous

How to add a UILongPressGestureRecognizer and UITapGestureRecognizer to the same control simultaneously?


It is similar to this question:

iPhone iOS how to add a UILongPressGestureRecognizer and UITapGestureRecognizer to the same control and prevent conflict?

but my problem is more complex.

I want to implement the same behavior you see in iOS 8 on iPad. I mean page grid in Safari.

The problem: one view should respond to both long press and tap gesture recognizers. The following things should work:

1)close button accepts clicks

2)when the tap begins the selected view should perform scale animation

3)on long press the selected view becomes draggable

If I don't use (requireGestureRecognizerToFail:) then tap gesture doesn't work. If I use this method then everything works but the long press events take place with huge delays.

How to solve this issue.


Solution

  • You need to use the requireGestureRecognizerToFail method.

    //Single tap
            UITapGestureRecognizer *tapDouble = [[UITapGestureRecognizer alloc]
                                                 initWithTarget:self
                                                 action:@selector(handleTapGestureForSearch:)];
            tapDouble.numberOfTapsRequired = 1;
            tapDouble.delegate = self;
            [self addGestureRecognizer:tapDouble];
    
            //long press
            UILongPressGestureRecognizer *longPressGestureRecognizer=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleLongPressRecognizer:)];
            longPressGestureRecognizer.numberOfTouchesRequired=1;
            longPressGestureRecognizer.minimumPressDuration = 0.5f;
            [longPressGestureRecognizer requireGestureRecognizerToFail:tapDouble];
            longPressGestureRecognizer.delegate = self;
            [self addGestureRecognizer:longPressGestureRecognizer];
    

    This means Long press gesture wait for the single Tap.