iOS - TapGestureRecognizer - 点击适用于整个屏幕而不是视图
Posted
技术标签:
【中文标题】iOS - TapGestureRecognizer - 点击适用于整个屏幕而不是视图【英文标题】:iOS - TapGestureRecognizer - Tap is applicable for the whole screen not for a view 【发布时间】:2013-12-12 08:35:17 【问题描述】:在我的应用中,我有一张图片和一个UITextView
。
我为这两个视图创建了一个UITapGestureRecognizer
,但问题是无论我在屏幕上单击什么位置,都只会执行与UITextView
关联的方法。
即使我单击图像,也只会执行与UITextView
关联的UITapGestureRecognizer
方法。
以下是我实现的代码:
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"];
我确定我在这里遗漏了一些东西。 据我所知,故事板中的关联是正确的。
请指正我哪里出错了
感谢您的宝贵时间
【问题讨论】:
你设置 imageView.userInteractionEnabled = YES 了吗? 【参考方案1】:你不应该在 self.view 上添加手势。
它应该被添加到您要识别点击事件的视图中。
【讨论】:
【参考方案2】:您在[self view]
对象上设置了两个点击手势对象。
此外,UIImageView
对象,我们称之为imageObj
,应该有userInteractionEnabled = YES
。
代替:
[[self view] addGestureRecognizer:tapGestureRecognizerImage];
你应该这样做:
[imageObj setUserInteractionEnabled:YES];
[imageObj addGestureRecognizer:tapGestureRecognizerImage];
您通常在您希望手势对象处理的对象上使用-addGestureRecognizer:
。
假设您有一个名为 myTapGesture
的 UITapGestureRecognizer
对象。
然后,让它工作......
-
在
UILabel *lblSomeObj
上将是:
[lblSomeObj addGestureRecognizer:myTapGesture];
在UIView *vwSomeObj
上将是:
[vwSomeObj addGestureRecognizer:myTapGesture];
等等……
【讨论】:
【参考方案3】:只需在各自的视图中添加手势,而不是在 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】:在 UIImageView 对象上添加手势并确保图像视图 userInteractionEnabled
设置为 YES
imageObj.userInteractionEnabled = YES;
[imageObj addGestureRecognizer:tapGestureRecognizerImage];
【讨论】:
【参考方案5】:你需要包含这段代码:-
[tapGestureRecognizerImage requireGestureRecognizerToFail:tapGestureRecognizer];
[imageObj addGestureRecognizer:tapGestureRecognizerImage];
【讨论】:
以上是关于iOS - TapGestureRecognizer - 点击适用于整个屏幕而不是视图的主要内容,如果未能解决你的问题,请参考以下文章