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

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

问题描述

我有3个UIViews,分层在一个大的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的自定义实现中,检查触摸设置中的每一次触摸。 hitTest方法的点可以使用

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;

方法,其中视图是你的superView(包含其他视图的视图)。

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];
}

我希望这有用,
Paul

I hope this was helpful, Paul

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

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