问题
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:
Update 1:
Before someone gets confused with xib, I must say that UIButtons
are set to Custom type so they are invisible under UIImageView
.
回答1:
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.
来源:https://stackoverflow.com/questions/15524683/getting-wrong-uibutton-tag-on-long-press-gesture-recognizer