2

I am working on a sample of Pan Gesture. I am keen to know that can I add single gesture on two views?

My code is as follows:

UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(invokePanGesture:)];
[panGesture setMinimumNumberOfTouches:1];
[panGesture setMaximumNumberOfTouches:2];

[btnGreen addGestureRecognizer:panGesture];
[btnYellow addGestureRecognizer:panGesture];

my handler method is as follows:

- (void)invokePanGesture:(UIPanGestureRecognizer*)recognizer {
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, 
                                     recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}

The problem now is gesture recognizer is considering only last view in my case btnYellow as its view. If I create two separate GestureRecognizer object it works. So please clear me that:

  1. Is it possible to have single gesture in multiple views or not?

  2. If yes then how?

  3. If now then why?

Thanks in Advance

Gajendra K Chauhan
  • 3,387
  • 7
  • 40
  • 55
Kapil Choubisa
  • 5,152
  • 9
  • 65
  • 100

3 Answers3

5

From the docs for UIGestureRecognizer

A gesture recognizer operates on touches hit-tested to a specific view and all of that view’s subviews. It thus must be associated with that view. To make that association you must call the UIView method addGestureRecognizer:. A gesture recognizer does not participate in the view’s responder chain.

So, in summary the only way a GestureRecognizer can operate on more than one view is if the recognizer operates on a superview of the other views.

Damo
  • 12,840
  • 3
  • 51
  • 62
3

I don't think it's possible.

Please have a look at https://stackoverflow.com/a/5567684/470964.

Also https://stackoverflow.com/a/7883902/470964: Maybe it's also a solution for your problem. I think the answer is that the GestureRecognizer has only one view property, that will be set.

Community
  • 1
  • 1
Sebastian
  • 3,379
  • 2
  • 23
  • 39
0

Can't you just write your invokePanGesture method to do the same thing to both views at the same time?

tobinjim
  • 1,862
  • 2
  • 19
  • 31
  • I can't because I want to know that on which view the gesture is invoked and move that view only. If I do the same you are saying than it won't work. It will keep the both view object with same frame according to you. – Kapil Choubisa May 04 '12 at 04:17
  • Then why use a single gesture recognizer? – tobinjim May 04 '12 at 12:09