7

I am creating a custom UIView and adding a UITapGestureRecognizer on it. I have a handler for the tap gesture. But at the same time I want my UIView to listen to touchesBegan & touchesEnded methods. I have implemented gestureRecognizer:shouldReceiveTouch: method also but touchesBegan/touchesEnded methods does not get called. Any clue why?

Inside my custom UIView

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)iGestureRecognizer shouldReceiveTouch:(UITouch *)iTouch {
    return YES;
}

Inside my view controller

MyCustomView aCustomView = [[[MyCustomView alloc] init] autorelease];
                UIGestureRecognizer *myGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
[aCustomView addGestureRecognizer:myGestureRecognizer];
                [myGestureRecognizer release];
Abhinav
  • 37,684
  • 43
  • 191
  • 309

2 Answers2

10

You need to set cancelsTouchesInView (and likely delaysTouchesBegan and delaysTouchesEnded) to NO for the gesture recognizer. The default behavior of a gesture recognizer is to avoid having both it and the view process the touch. These settings let you fine-tune that behavior.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • I sure wish I was getting that behaviour you mention. I am using the default settings, yet my touches methods still get called. See my question here: http://stackoverflow.com/questions/15869944/how-to-prioritize-gesture-recognizers-and-touches-in-a-uiview – johnbakers Apr 08 '13 at 01:58
  • @RobNapier would failing to put cancelsTouchesInView be linked to my issue here: https://stackoverflow.com/questions/46170876/random-crash-on-pickerview-didselect-cfrunloop-is-calling-out-to-a-source1-p?noredirect=1#comment79305779_46170876 – user2363025 Sep 15 '17 at 09:33
0

As stated earlier, you need to set the cancelTouchesInView property to NO on your UITapGestureRecognizer.

From the Apple Docs:

cancelsTouchesInView—If a gesture recognizer recognizes its gesture, it unbinds the remaining touches of that gesture from their view (so the window won’t deliver them). The window cancels the previously delivered touches with a (touchesCancelled:withEvent:) message. If a gesture recognizer doesn’t recognize its gesture, the view receives all touches in the multi-touch sequence.

Further reading: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIGestureRecognizer_Class/

JaredH
  • 2,338
  • 1
  • 30
  • 40