检测某些 UIView 是否在其他 UIView 中被触摸 [英] Detect if certain UIView was touched amongst other UIViews

查看:17
本文介绍了检测某些 UIView 是否在其他 UIView 中被触摸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 3 个 UIView,位于一个大的 uiview 之上.我想知道用户是否触摸顶部的而不关心其他的.我将在第二个 UIView 中有几个按钮,在第三个 UIView 中有一个 UITable.

I have 3 UIViews, layered on top of one large uiview. I want to know if the user touches the top one and not care about the other ones. I will have a couple of buttons in the second UIView and a UITable in the 3rd UIView.

问题是我在第一个视图上打开 userInteractionEngabled 并且有效,但所有其他视图即使我关闭它也以相同的方式响应.如果我在 self.view 上禁用 userInteractionEnabled,他们都不会响应.我也无法检测到在 touchesBegan 委托方法中触摸了哪个视图.

Problem is I turn userInteractionEngabled on on the first view and that works, but all the other views respond in the same way even if I turn it off. If I disable userInteractionEnabled on self.view none of them respond. I also can't detect which view was touched in the touchesBegan delegate method.

我的代码:

UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 150)];
aView = userInteractionEnabled = YES;
[self.view addSubview:aView];

UIView *bView = [[UIView alloc] initWithFrame:CGRectMake(0, 150, 320, 50)];
bView.userInteractionEnabled = NO;
[self.view addSubview:bView];

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//This gets called for a touch anywhere
}

推荐答案

为了检查另一个视图中的某个视图是否被触摸,您可以使用hitTest.

In order to check whether certain view inside another view was touched you can use hitTest.

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event;

在您自定义的 touchesBegan 实现中,检查 touches set 中的每一个 touch.可以使用

In your custom implementation of touchesBegan check every touch in touches set. The point for hitTest method can be obtained using

- (CGPoint)locationInView:(UIView *)view;

方法,其中视图是您的超级视图(包含其他视图的视图).

method, where the view is your superView (the one that contains other views).

这是一个快速的自定义实现:

Here's a fast custom implementation:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    CGPoint locationPoint = [[touches anyObject] locationInView:self];
    UIView* viewYouWishToObtain = [self hitTest:locationPoint withEvent:event];
}

希望对你有帮助保罗

这篇关于检测某些 UIView 是否在其他 UIView 中被触摸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆