3

I am aware that there are already many questions asked similar to this, but I have tried all of them, and on failing to solve my issue I am posting my question. First the questions I tried are:

1)How to get button.tag via longPressGestureRecognizer?

2)UIButton Long Press Event

In my application I have 12 UIButtons in my xib. On the long press of UIButton I have this method getting called. Using gesture.view.tag property always gives me same tag(i.e) every time when I click on different UIButtons.

- (IBAction)longPress:(id)sender {

     UILongPressGestureRecognizer* gesture=(UILongPressGestureRecognizer*)sender;
     NSLog(@"Tag---> %d",gesture.view.tag);
  }

My xib looks something like this:

enter image description here

Update 1:

Before someone gets confused with xib, I must say that UIButtons are set to Custom type so they are invisible under UIImageView.

Community
  • 1
  • 1
rohan-patel
  • 5,772
  • 5
  • 45
  • 68
  • It will crash. Sender is `UILongPressGestureRecognizer`. It does not have tag property. it's view that is `UIButton` will have tag property. Kindly refer to [Richard j Ross's](http://stackoverflow.com/users/427309/richard-j-ross-iii) answer. Thanks for your efforts. – rohan-patel Mar 20 '13 at 13:29
  • 1
    Yep I noticed in regard to the Gesture Recognizer, I believe RJR's solution is correct – dsgriffin Mar 20 '13 at 13:30

1 Answers1

7

It appears that a UIGestureRecognizer can be tracking more than one view, but it does not report that it is tracking more than one view. Thus, when you check the view property of a UIGestureRecognizer, it is set to the last view that the recognizer was added to.

From the docs:

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.

The solution in this scenario is to have a gesture recognizer for each view that needs recognizing, and have them linked to the same delegate selector.

Note: this question (and my answer) originated in the NSChat chat room, on March 20th, 2013. It was decided to post here for future reference.

Community
  • 1
  • 1
Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201