rohan-patel
rohan-patel

Reputation: 5782

Getting wrong UIButton tag on Long press gesture recognizer

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.

Upvotes: 3

Views: 2087

Answers (1)

Richard J. Ross III
Richard J. Ross III

Reputation: 55573

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.

Upvotes: 7

Related Questions