How to get button.tag via longPressGestureRecognizer?

南楼画角 提交于 2019-12-10 15:15:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!