Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 292
Joshua Goossen Avatar asked Jul 07 '12 22:07

Joshua Goossen


2 Answers

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.

like image 188
LearnCocos2D Avatar answered Sep 20 '22 18:09

LearnCocos2D


In order to add more than one UIGestureRecognizer onto the same view, you need to set the delegate property of the gesture recognizers you added onto the view and implement the following method in the delegate:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

By the way above, you can add multiple gesture recognizers onto the same view, no matter whether the gesture recognizers are the same type or not.

For example, you can add two UITapGestureRecognizer onto the same view and the callbacks of the two tap gesture recognizers will be called. And the last added callback will be called first.

Hope this helps.

like image 25
HongchaoZhang Avatar answered Sep 23 '22 18:09

HongchaoZhang