Search code examples
uiviewcocos2d-iphoneuitapgesturerecognizer

Adding Multiple UITapGestureRecognizers to single view (Cocos2d)


I am adding the following code in the onEnter method.

doubleTapRecognizer_ = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    doubleTapRecognizer_.numberOfTapsRequired = 2;
    doubleTapRecognizer_.cancelsTouchesInView = NO;
    [[[CCDirector sharedDirector] view] addGestureRecognizer:doubleTapRecognizer_];

I have multiple instances of this class, but the only one that gets it's selector called is the last instance added. The UIView Class Reference leads me to believe that it is possible to add more than one UIGestureRecognizer to a single view. The property "gestureRecognizers" returns an NSArray.

In fact I already have a UIPanGestureRecognizer working with the same view from another class. So I am getting at least two UIGestureRecognizers to work at once.


Solution

  • You can add multiple gesture recognizers to the same view. What you can't (easily) do is add multiple instances of the same gesture recognizer type (pan, swipe, double-tap, etc) to the same view.

    Why?

    Because as soon as the first gesture recognizer recognizes the gesture (double tap in this case) it cancels all touch events. Therefore the remaining gesture recognizers will never finish recognition, and will never fire their events.

    You do not need more than one gesture recognizer of the same type. In your case, once you've received the double-tap event, it's up to you to signal the right object that it was double-tapped. Use the recognizer's position and other attributes to find, for example, the sprite that was double-tapped and then have it do whatever it needs to do.

    For that reason it's good design to let the gestures be recognized by a higher-level node in your scene hierarchy (ie the UI layer) which then passes on the events to the appropriate nodes, or simply ignores it.