Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two UILongPressGestureRecognizer, one can fire, the other cannot

guys,

I have added two UILongPressGestureRecognizer. What I want is when two buttons are pressed down for 0.3 second, fire up "shortPressHandler". If user keeps pressing these two buttons for another 1.2 second, fire up "longPressHandler". Now I only get shortPressHandler fired up and the longPressHandler was never fired. I think it might because the shortPressGesture is recognized first and longPressGesture never gets a chance. Can anyone show me how to achieve what I want? Thanks in advance.

UILongPressGestureRecognizer *longPressGesture =[[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressHandler:)] autorelease];
longPressGesture.numberOfTouchesRequired = 2;
longPressGesture.minimumPressDuration = 1.5;
longPressGesture.allowableMovement = 10;
longPressGesture.cancelsTouchesInView = NO;
longPressGesture.enabled = true;
[self.view addGestureRecognizer:longPressGesture];

UILongPressGestureRecognizer *shortPressGesture =[[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(shortPressHandler:)] autorelease];
shortPressGesture.numberOfTouchesRequired = 2;
shortPressGesture.minimumPressDuration = 0.3;
shortPressGesture.allowableMovement = 10;
shortPressGesture.cancelsTouchesInView = NO;
shortPressGesture.enabled = true;
[self.view addGestureRecognizer:shortPressGesture];
like image 507
Globalhawk Avatar asked Mar 15 '12 11:03

Globalhawk


Video Answer


1 Answers

Insert this line before adding shortPressGesture:

 [shortPressGesture requireGestureRecognizerToFail:longPressGesture];

Note: shortGesture will not get called immediately after 0.3 seconds of holding but when the tap is released if it was between 0.3 seconds and 1.2 seconds long. If the tap is longer than 1.2 s (you have 1.5s in your code which is probably a typo) only longPressGesture will fire up.

EDIT:

However, if you want your event handlers both to fire (in an event of long press), you should do this:

Your UIView of should implement the <UIGestureRecognizerDelegate> in .h file.

In .m file you add this method:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {

    return YES;
}

Now instead of adding the line:

[shortPressGesture requireGestureRecognizerToFail:longPressGesture];

You add this two lines:

shortPressGesture.delegate = self;
longPressGesture.delegate = self;

NOTE: if you have any other UIGestureRecognisers linked to your UIVIew you will have to add some checking in shouldRecognizeSimultaneouslyWithGestureRecognizer:, otherwise you can simply return YES.

like image 175
Rok Jarc Avatar answered Oct 13 '22 06:10

Rok Jarc