iOS - UITapGestureRecognizer - Tap适用于整个屏幕而不适用于视图

时间:2013-12-12 08:35:17

标签: ios objective-c cocoa-touch uitapgesturerecognizer

在我的应用中,我有一张图片和UITextView 我为这两个视图创建了一个UITapGestureRecognizer,但问题是无论我在屏幕上点击什么,只会执行与UITextView相关联的方法。
即使我点击图片,也只会执行与UITapGestureRecognizer相关联的UITextView方法。

以下是我实施的代码:

UITapGestureRecognizer *tapGestureRecognizerImage = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                            action:@selector(handleTapFromImage:)];
[infobutton addGestureRecognizer:tapGestureRecognizerImage];
[[self view] addGestureRecognizer:tapGestureRecognizerImage];

UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                       action:@selector(handleTapFrom:)];
[messageOne addGestureRecognizer:tapGestureRecognizer];
[[self view] addGestureRecognizer:tapGestureRecognizer];

//The following are the methods associated
- (void) handleTapFrom: (UITapGestureRecognizer *)recognizer {
    //Code to handle the gesture
    NSLog(@"I am in handleTapFrom method");
}

- (void) handleTapFromImage: (UITapGestureRecognizer *)recognizer {
    //Code to handle the gesture
    NSLog(@"I am in handleTapFrom Image method");
    [self.view makeToast:@"Your verification code does not match. Re-enter your verification code"];
}

我确信我在这里遗漏了一些东西 故事板中的关联对我来说是正确的。

请纠正我出错的地方

感谢您的时间

5 个答案:

答案 0 :(得分:3)

你不应该在self.view上添加手势。

它应该添加到您想要识别点按事件的视图上。

答案 1 :(得分:1)

您正在[self view]对象上设置点击手势对象 另外,UIImageView对象,我们称之为imageObj,应该有userInteractionEnabled = YES

而不是:

[[self view] addGestureRecognizer:tapGestureRecognizerImage];

你应该这样做:

[imageObj setUserInteractionEnabled:YES];
[imageObj addGestureRecognizer:tapGestureRecognizerImage];

您通常在希望手势对象使用的对象上使用-addGestureRecognizer: 假设您有一个名为UITapGestureRecognizer的{​​{1}}对象。

然后,让它工作......

  1. myTapGesture上会是:
    • UILabel *lblSomeObj
  2. [lblSomeObj addGestureRecognizer:myTapGesture];上会是:
    • UIView *vwSomeObj
  3. 等...

答案 2 :(得分:1)

您需要包含以下代码: -

 [tapGestureRecognizerImage requireGestureRecognizerToFail:tapGestureRecognizer]; 
[imageObj addGestureRecognizer:tapGestureRecognizerImage];

答案 3 :(得分:1)

只需在相应的视图中添加手势,而不是在self.view中添加。

 UITapGestureRecognizer *tapGestureRecognizerImage = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapFromImage:)];

[infobutton addGestureRecognizer:tapGestureRecognizerImage];

UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapFrom:)];
[messageOne addGestureRecognizer:tapGestureRecognizer];

答案 4 :(得分:1)

在UIImageView对象上添加手势,并确保将图片视图userInteractionEnabled设置为YES

imageObj.userInteractionEnabled = YES;
[imageObj addGestureRecognizer:tapGestureRecognizerImage];