2014-07-19 36 views
1

有沒有辦法根據它們在屏幕上的位置來檢索對象/對象(即UILabel,UIButton,UIView等)?例如,我怎樣才能找出坐在(100,100)點之上的元素?iOS:根據屏幕上的位置查找對象?

我問的原因是因爲我想訪問位於特定點的最頂端對象的backgroundColor屬性?

回答

0

可以獲得場景中某個點的顏色,但不知道是否可以在那裏識別對象。 用於在屏幕中的某一點獲取顏色是一種解決方案。考慮像

CGPoint aPoint = CGPointMake(100, 100); 

在sceen一個點,你可以在這一點上得到的顏色與IOS Core Graphics框架的幫助下,sceen像

unsigned char pixel[4] = {0}; 

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, kCGBitmapAlphaInfoMask & kCGImageAlphaPremultipliedLast); 

CGContextTranslateCTM(context, -aPoint.x, -aPoint.y); 

[self.view.layer renderInContext:context]; 

CGContextRelease(context); 
CGColorSpaceRelease(colorSpace); 

UIColor *color = [UIColor colorWithRed:pixel[0]/255.0 green:pixel[1]/255.0 blue:pixel[2]/255.0 alpha:pixel[3]/255.0]; 
0

UIView's方法- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event不正是你想要的。

UIView *hitView = [self.view hitTest:location withEvent:nil]; 

根據文檔它Returns the farthest descendant of the receiver in the view hierarchy (including itself) that contains a specified point.

This method ignores view objects that are hidden, that have disabled user interactions, or have an alpha level less than 0.01. This method does not take the view’s content into account when determining a hit. Thus, a view can still be returned even if the specified point is in a transparent portion of that view’s content.

如果你想排除的看法也一樣,你將不得不爲此編寫你自己的遞歸方法。類似的東西(仍然沒有考慮到視圖的內容):

- (UIView *)getHitView:(UIView*)parent location:(CGPoint)location{ 
    for(UIView *v in parent.subviews.reverseObjectEnumerator){ 
     if(CGRectContainsPoint(v.frame, location)){ 
      return [self getHitView:v location:[v convertPoint:location fromView:parent]]; 
     } 
    } 
    return parent; 
}