ios - 在 UILongPressGestureRecognizer 上无法检测到右(按下)按钮?

标签 ios objective-c uigesturerecognizer

关于 SO ( UILongPressGestureRecognizer ) 的答案很少,但我无法使用以下代码获得正确的值,不确定我做错了什么。在 SO 和类似的第三方网站教程上尝试了更多页面,但无法获得确切的按钮详细信息。

@property (nonatomic,strong) UILongPressGestureRecognizer *lpgr;
@property (strong, nonatomic) IBOutlet UIButton *button1;
@property (strong, nonatomic) IBOutlet UIButton *button2;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressGestures:)];
    self.lpgr.minimumPressDuration = 2.0f;
    self.lpgr.allowableMovement = 100.0f;
    [self.view addGestureRecognizer:self.lpgr];
}

- (void)handleLongPressGestures:(UILongPressGestureRecognizer *)gesture
{
    if ([gesture isEqual:self.lpgr]) {

        if (gesture.state == UIGestureRecognizerStateBegan)
        {
            if (gesture.view == self.button1) {
                NSLog(@"Button 1 is pressed for long");
            }else if(gesture.view == self.button2) {
                NSLog(@"Button 2 is pressed for long");
            }else{
                NSLog(@"another UI element is pressed for long");
            }

        }

    }
}

每次长按按钮时,我都会收到 NSLog(@"另一个 UI 元素被长按");

最佳答案

else 语句每次都会被触发,因为您正在将手势添加到主视图。即使您长按按钮,事件也会传递到您正在捕获它的 View 。如果您在 viewDidLoad 中添加以下行,它将适本地触发按钮。

[self.button1 addGestureRecognizer:self.lpgr];
[self.button2 addGestureRecognizer:self.lpgr];

关于ios - 在 UILongPressGestureRecognizer 上无法检测到右(按下)按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32340496/

相关文章:

iOS:在 Interface Builder 中创建具有动态 contentSize 的 UIScrollView

ios - 试飞问题 : can only install app on devices that were plugged in directly

ios - Firebase - 在没有安全节点的情况下获取数据?

ios - Objective-C 完整的 UIView 到 PDF

ios - 为什么UIWindow添加UIGestureRecognizer后iPad无响应?

ios - 禁用隐藏导航栏的触摸

ios - 同时使用多个 UIGestureRecognizers,例如 Swift 3 中的 UIRotationGestureRecognizer 和 UIPanGestureRecognizer

iphone - 图像缩放、 ScrollView 、裁剪

ios - 如何切换cocoapod版本

ios - UIActionSheet 按钮转入新的 ViewController