UILongPressGestureRecognizer

UILongPressGestureRecognizer

我用以下代码将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没有标签属性。

最佳答案

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

-(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是您的按钮属性。是的,使用==适合检查手势视图是否为按钮之一,因为您的确要比较对象指针。

关于ios - 要知道触发了哪个UILongPressGestureRecognizer,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17518590/

10-09 02:44