4

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?
}
yosh
  • 3,245
  • 7
  • 55
  • 84

2 Answers2

14

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;
}
Marko Hlebar
  • 1,973
  • 17
  • 18
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]);
saadnib
  • 11,145
  • 2
  • 33
  • 54