问题
I'm dynamically adding image buttons to some scrollview. They all point at one longPressHandler. Now, how do I get which button was pressed? The [sender tag] gives me the tag of longGestureRecognizer that I added to button and I can't manually set that tag.
for (...) {
UIButton *button = [[UIButton alloc] init];
button.tag = w + h * 3;
[button addTarget:self action:@selector(imageButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
UILongPressGestureRecognizer *gest = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(imageButtonLongPress:)];
gest.minimumPressDuration = 1;
gest.delegate = self;
[button addGestureRecognizer:gest];
[gest release];
[scrollView addSubview:button];
[button release];
}
- (void) imageButtonLongPress:(id)sender {
// how to get button tag here?
}
回答1:
There is a view
property in the UIGestureRecognizer
which returns the view that recognizer is attached to. I think that is your best bet.
- (void) imageButtonLongPress:(id)sender {
UIGestureRecognizer *recognizer = (UIGestureRecognizer*) sender;
int tag = recognizer.view.tag;
}
回答2:
In your action you have to type cast your sender in gesture and then type cast its view to a button then get button's tag as -
UILongPressGestureRecognizer *gest = (UILongPressGestureRecognizer *)sender;
UIButton *button = (UIButton*)[gest view];
NSLog(@"%d",[button tag]);
来源:https://stackoverflow.com/questions/5700984/how-to-get-button-tag-via-longpressgesturerecognizer