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

时间:2015-09-01 20:39:35

标签: 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元素被按下很长时间”);

2 个答案:

答案 0 :(得分:1)

The else statement is being hit every time because you are adding the gesture to the main view. Even when you are long pressing on the button the event is being passed up to the view where you are catching it. If you add the lines below in viewDidLoad it will fire on the buttons appropriately.

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

答案 1 :(得分:1)

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