如何通过长按手势获取按钮的tag?

4

我正在向一些滚动视图动态添加图像按钮。它们都指向一个长按处理程序。现在,我如何知道哪个按钮被按下了?[sender 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?
}
2个回答

14

UIGestureRecognizer中有一个view属性,它返回识别器所附加到的视图。我认为这是你最好的选择。

- (void) imageButtonLongPress:(id)sender {  
    UIGestureRecognizer *recognizer = (UIGestureRecognizer*) sender;
    int tag = recognizer.view.tag;
}

recognizer.view.tag 给我错误的 UIButton 点击标签。有什么解决办法吗? - rohan-patel

2
在你的操作中,你需要将手势中的发送者进行类型转换,然后将其视图转换为按钮,然后获取按钮的标签,如下所示 -
UILongPressGestureRecognizer *gest = (UILongPressGestureRecognizer *)sender;
UIButton *button = (UIButton*)[gest view];
NSLog(@"%d",[button tag]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接