2010-05-08 76 views
28

我有3个UIView,分层在一个大型uiview之上。我想知道用户是否触及顶级用户而不关心其他用户。我将在第二个UIView中有几个按钮,在第三个UIView中有一个UITable。检测某些UIView是否在其他UIView中被触及

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

我的代码:

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 
} 

回答

58

为了检查另一视图中的某些观点是否被感动了,你可以使用则hitTest。

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

在您自定义的touchesBegan实现中,检查触摸设置中的每个触摸。可使用

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

方法,其中,所述视图是上海华(包含其它视图的)来获得对则hitTest方法的点。

编辑:这里有一个快速自定义实现:

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

我希望这是有帮助的, 保罗

+0

对不起,我知道你在正确的轨道上,但我有点麻烦,你完全不知道你在说什么。我得到了从您的locationInView接触触及的点,我可以在技术上确定用户触摸哪个uiview,但我不知道它是如何调用hitTest – Rudiger 2010-05-08 08:33:21

+2

应该注意的是,调用'locationInView:'参数为' nil'给你在主窗口坐标空间中的位置'CGPoint'。 – 2012-03-13 00:48:39

26

在我来说,我想找到的UIView不是由则hitTest返回。但是,下面的代码更好地工作:

CGPoint locationPoint = [[touches anyObject] locationInView:self.view]; 
    CGPoint viewPoint = [myImage convertPoint:locationPoint fromView:self.view]; 
    if ([myImage pointInside:viewPoint withEvent:event]) { 
     do something 
    } 
+0

我也遇到了接受答案的问题。无论出于何种原因,这也起到了作用。请注意,我还试图在UIImageView上检测命中,而不是仅在UIView中检测,如果这相关的话。 – 2014-06-22 23:36:25

8

的touchesBegan检查出被触摸的观点是你想要的,解决了这个问题对我来说,当我试图如果用户触摸的特定ImageView的鉴定。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 

    if ([touch view] == imageView) { 
     ... your code to handle the touch 
    } 
    ... 

如果调整视图diamensions内容确保相应否则更改视图大小它甚至会在区域识别触摸事件在该视图,使内容那里。在我的情况下,当我试图保持图像比例为UIViewContentModeScaleAspectFit虽然图像是根据需要在“空白”区域调整触摸事件。

12

这也可以通过以下方式完成。

首先找到在视图中触摸你所关心的位置:

CGPoint location = [touches.anyObject locationInView:viewYouCareAbout]; 

然后看如果点视图的范围内:

BOOL withinBounds = CGRectContainsPoint(viewYouCareAbout.bounds, location); 

那么,如果它的范围之内,执行你的行动。

CGRectContainsPoint(viewYouCareAbout.bounds, [touches.anyObject locationInView:viewYouCareAbout]) 
8

SWIFT代码:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
     if let touch = touches.first { 
      if touch.view == self.view { 
       self.hideInView() 
      } else { 
       return 
      } 

     } 
    } 
+0

很好的答案。与投票分享爱。 – 2016-07-07 16:06:59

0

这为我工作:

这可以用一个语句,例如,可以直接在if语句中使用完成

func respondToGesture(gesture: UIGestureRecognizer) { 
    let containsPoint = CGRectContainsPoint(targetView.bounds, gesture.locationInView(targetView)) 
}