How to get button.tag via longPressGestureRecognizer?
Asked Answered
O

2

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?
}
Origan answered 18/4, 2011 at 9:36 Comment(0)
N
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;
}
Nata answered 18/4, 2011 at 9:48 Comment(1)
recognizer.view.tag gives me wrong tag of UIButton clicked. Any solution?Balsam
K
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]);
Knowland answered 18/4, 2011 at 9:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.