要知道触发了哪个UILongPressGestureRecognizer

时间:2013-07-08 02:56:22

标签: ios objective-c uigesturerecognizer

我使用代码

UILongPressGestureRecognizer添加到多个UIButton
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(btnLong:)];
[btnOne addGestureRecognizer:longPress]; //there are btnTwo, btnThree for example

当我长按按钮时,会调用该方法:

-(void)btnLong:(UILongPressGestureRecognizer *)gestureRecognizer{

    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
    }
}  

我的问题是,我怎么知道触发了哪个UILongPressGestureRecognizer,因为UILongPressGestureRecognizer没有标记属性。

3 个答案:

答案 0 :(得分:3)

为每个按钮指定唯一的标签号。然后在您的操作方法中,您可以执行以下操作:

-(void)btnLong:(UILongPressGestureRecognizer *)gestureRecognizer{
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
        UIView *view = gestureRecognizer.view;
        if (view.tag == 1) { // first button's tag
            // process 1st button
        } else if (view.tag == 2) { // second button's tag
            // process 2nd button
        }
    }
}

另一种选择,如果您有每个按钮的插座,您可以这样做:

-(void)btnLong:(UILongPressGestureRecognizer *)gestureRecognizer{
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
        UIView *view = gestureRecognizer.view;
        if (view == self.firstButton) {
            // process 1st button
        } else if (view == self.secondButton) {
            // process 2nd button
        }
    }
}

其中firstButtonsecondButton是您的按钮属性。是的,使用==适合检查手势的视图是否是其中一个按钮,因为你的意思是比较对象指针。

答案 1 :(得分:0)

为什么不将手势录制在普通superview上?然后,您可以使用UIView确定长按的locationInView,然后访问视图的标记属性。

答案 2 :(得分:0)

我使用UIView作为tableview单元格的子视图。我将UILongGesture应用于此。这是为我工作的代码。

func handleLongPressGesture(_ longPressGestureRecognizer: UILongPressGestureRecognizer){

            if longPressGestureRecognizer.state == UIGestureRecognizerState.began
            {
                let touchPoint = longPressGestureRecognizer.location(in: tableViewObj)

                            if let indexPath = tableViewObj.indexPathForRow(at: touchPoint)
                            {
                                print(indexPath.row)



                }
            }
}

您有索引路径。你可以做任何你需要做的事。

相关问题