How to find which UIElement is present in the window when (x,y) coordinates is given in iOS ? I will be having a view controller with many UI elements and I will be given x,y with which I have to find the element present in the view .
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
To get a list of views at a particular point you can use,
-(NSArray*)subviewsAtPoint:(CGPoint)point inView:(UIView*)view {
NSMutableArray *viewsAtPoint = [[NSMutableArray alloc]init];
for(UIView *subview in view.subviews) {
if(CGRectContainsPoint(subview.frame, point))
[viewsAtPoint addObject:subview];
}
return viewsAtPoint;
}
To get the topmost view at a particular point, you can use
-(UIView *)topmostViewAtPoint:(CGPoint)point inView:(UIView*)view {
for(UIView *subview in view.subviews.reverseObjectEnumerator) {
if(CGRectContainsPoint(subview.frame, point))
return subview;
}
return view;
}
The above code assumes that there is only one level of subviews and there are no nested subviews.
If you have nested subviews, you can define a recursive function to find the topmost view.
-(UIView *)topmostViewAtPoint:(CGPoint)point inView:(UIView*)view {
for(UIView *subview in view.subviews.reverseObjectEnumerator) {
if(CGRectContainsPoint(subview.frame, point))
{
CGPoint innerPoint = [self.view convertPoint:point toView:subview];
[self topmostViewAtPoint:innerPoint inView:subview];
}
}
return view;
}
回答2:
A view may have multiple views at a given CGPoint
. This method should return an array subviews that are there at a given point.
-(NSArray*)viewsAtPoint:(CGPoint)point inView:(UIView*)view {
NSArray *subviews = view.subviews;
NSMutableArray *mutableArray = [[NSMutableArray alloc]init];
for(UIView *subview in subviews) {
CGPoint thisSubviewPoint = subview.frame.origin;
if(thisSubviewPoint.x == point.x && thisSubviewPoint.y == point.y) {
[mutableArray addObject:subview];
}
}
return mutableArray;
}