2010-05-08 51 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)) 
}