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

On a UILongPressGestureRecognizer unable to detect right(pressed) button?

关于 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(@"another UI element is pressed for long");

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

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

您已将手势添加到 self.view 而不是 button1/button2。