UIScrollView 和检测点击手势的子视图
我已将 TapGestureRecognizer 添加到我的 self.view 中:
tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
tap.numberOfTapsRequired = 1;
tap.numberOfTouchesRequired = 1;
[self.view addGestureRecognizer:tap];
[tap release];
该视图包含一个带有图像和标签的 UIScrollView。我想检测用户是否点击标签。
- (void)singleTap:(UIGestureRecognizer*)gestureRecognizer {
CGPoint pt = [gestureRecognizer locationInView:self.view];
UIView *v = [self.view hitTest:pt withEvent:nil];
if ([v isKindOfClass:[UILabel class]]) {
NSLog(@"label!");
return;
}
// else do other stuff if its not a label
但我没有看到标签!在我的日志中。
I've added a TapGestureRecognizer to my self.view:
tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
tap.numberOfTapsRequired = 1;
tap.numberOfTouchesRequired = 1;
[self.view addGestureRecognizer:tap];
[tap release];
The view contains a single UIScrollView with images and labels. I want to detect if the user taps on a label or not.
- (void)singleTap:(UIGestureRecognizer*)gestureRecognizer {
CGPoint pt = [gestureRecognizer locationInView:self.view];
UIView *v = [self.view hitTest:pt withEvent:nil];
if ([v isKindOfClass:[UILabel class]]) {
NSLog(@"label!");
return;
}
// else do other stuff if its not a label
However I don't see the label! in my log.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这是因为
UILabel
上的userInteractionEnabled
默认为NO
。尝试打开它。编辑:这确实是一个猜测,但只是为了确认,Apple 文档在
[UIView hitTest:withEvent:]
上声明:I think it's because
userInteractionEnabled
is by defaultNO
onUILabel
s. Try turning that on.EDIT: It was really a guess, but just to confirm, Apple docs on
[UIView hitTest:withEvent:]
state:您的子视图(例如标签本身)实际上隐藏了底层视图的用户交互。
为什么不将手势识别器添加到您的标签中。
或者,您可能想使用 UIButton 作为标签。
或者 -
如果您不想确定哪个标签被触摸,您可能需要在所有标签之上添加一个不可见视图(一个空视图,既不是隐藏视图,也不是 alpha=0 的视图),并将手势识别器添加到那些。
Your subviews, such as the labels themself, actually hide the user interactions from the underlying view.
Why don't you add the gesture recognizers to your label(s).
Alternatively you may want to use UIButton for the labels.
Or -
if you do not want to determine which label has been touched, you may want to add an invisible view (an empty view, neither a hidden one nor one with alpha=0) on top of all labels and add the gesture recognizers to those.