2010-09-28 76 views
10

UIScrollView包含多個UIView對象;如何判斷屏幕上不是由觸摸產生的點是否在滾動視圖的特定子視圖內?到目前爲止,嘗試確定點是否在子視圖中總是返回父滾動視圖的子視圖數組中的第一個子視圖,即,座標是相對於滾動視圖而不是窗口。確定屏幕上的點是否在特定的UIScrollView子視圖中

這裏是我試過(編輯)

-(UIView *)viewVisibleInScrollView 
{ 
    CGPoint point = CGPointMake(512, 384); 
    for (UIView *myView in theScrollView.subviews) 
    { 
     if(CGRectContainsPoint([myView frame], point)) 
     { 
      NSLog(@"In View"); 
      return myView; 
     } 
    } 
    return nil; 
} 
+0

- (UIView的*)viewVisibleInScrollView { \t CGPoint點= CGPointMake(512,384); \t爲(UIView的*在theScrollView.subviews MyView的){ \t \t如果(CGRectContainsPoint([MyView的幀],點)){ \t \t \t的NSLog(@ 「以查看」); \t \t \t return myView; \t \t} \t} \t return nil; } – Kyle 2010-09-28 20:18:28

回答

14

它看起來像你的一點是相對於窗口,你希望它相對於當前視圖。 convertPoint:fromView:應該對此有所幫助。

可能有錯誤在這裏,但它應該是這個樣子:

-(UIView *)viewVisibleInScrollView 
{ 
    CGPoint point = CGPointMake(512, 384); 
    CGPoint relativePoint = [theScrollView convertPoint:point fromView:nil]; // Using nil converts from the window coordinates. 
    for (UIView *myView in theScrollView.subviews) 
    { 
     if(CGRectContainsPoint([myView frame], relativePoint)) 
     { 
      NSLog(@"In View"); 
      return myView; 
     } 
    } 
    return nil; 
} 
+4

-1。 '-frame'在父節點的座標空間中。您應該比較'-bounds',或者將其轉換爲滾動視圖的座標空間*一次*並與'-frame'比較。 – 2010-09-28 23:53:10

+0

好的。我已經適當地調整了代碼。 – 2010-09-28 23:59:16

+0

這工作完美。謝謝,感覺我好像很親密。 – Kyle 2010-09-29 02:44:15

2

這是我做的:

@implementation UIScrollView (FOO) 
- (id)foo_subviewAtPoint:(CGPoint)point 
{ 
    point.x += self.contentOffset.x; 
    for (UIView *subview in self.subviews) { 
     if (CGRectContainsPoint(subview.frame, point)) { 
      return subview; 
     } 
    } 
    return nil; 
} 
@end 

下面是我如何使用它:

CGPoint center = [scrollView convertPoint:scrollView.center fromView:scrollView.superview]; 
UIView *view = [scrollView foo_subviewAtPoint:center]; 

有些事情要注意:

  • 傳遞給foo_subviewAtPoint:的點是,用滾動視圖的座標系表示。這就是爲什麼在上面的代碼中,我必須將center轉換爲其超級視圖的座標系。
  • 我正在使用iOS 6.1及更高版本的佈局。我從來沒有用其他的測試過這個代碼,所以YMMV。
相關問題