简体   繁体   English

UIScrollView和检测轻击手势的子视图

[英]UIScrollView and detecting subview of tap gesture

I've added a TapGestureRecognizer to my self.view: 我在自己的视图中添加了一个TapGestureRecognizer:

    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. 该视图包含带有图像和标签的单个UIScrollView。 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. 在我的日志中。

I think it's because userInteractionEnabled is by default NO on UILabel s. 我认为这是因为UILabel默认情况下userInteractionEnabledNO Try turning that on. 试着打开它。

EDIT: It was really a guess, but just to confirm, Apple docs on [UIView hitTest:withEvent:] state: 编辑:这真的是一个猜测,但只是为了确认,Apple文档在[UIView hitTest:withEvent:]状态:

This method ignores view objects that are hidden, that have disabled user interaction, or have an alpha level less than 0.01. 此方法忽略隐藏的视图对象,禁用用户交互或alpha级别小于0.01的视图对象。

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. 或者,您可能希望使用UIButton作为标签。

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. 如果您不想确定触摸了哪个标签,您可能希望在所有标签的顶部添加一个不可见的视图(一个空视图,既不是隐藏的视图也不是一个alpha = 0的视图),并将手势识别器添加到这些视图中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM