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

发布于 2024-12-01 22:04:10 字数 724 浏览 0 评论 0原文

我已将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

提笔落墨 2024-12-08 22:04:10

我认为这是因为 UILabel 上的 userInteractionEnabled 默认为 NO。尝试打开它。

编辑:这确实是一个猜测,但只是为了确认,Apple 文档在 [UIView hitTest:withEvent:] 上声明:

此方法会忽略隐藏的视图对象、禁用用户交互的视图对象或 Alpha 级别小于 0.01 的视图对象。

I think it's because userInteractionEnabled is by default NO on UILabels. Try turning that on.

EDIT: It was really a guess, but just to confirm, Apple docs on [UIView hitTest:withEvent:] state:

This method ignores view objects that are hidden, that have disabled user interaction, or have an alpha level less than 0.01.

再浓的妆也掩不了殇 2024-12-08 22:04:10

您的子视图(例如标签本身)实际上隐藏了底层视图的用户交互。

为什么不将手势识别器添加到您的标签中。
或者,您可能想使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文