在iOS中从x,y查找对象 [英] FInd the object from x,y in iOS
问题描述
当在iOS中给出(x,y)坐标时,如何查找窗口中存在哪个UIElement?我将拥有一个包含许多UI元素的视图控制器,并且将得到x,y,我必须使用x,y查找视图中存在的元素。
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 .
推荐答案
要获取可以使用的特定点的视图列表,
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;
}
这篇关于在iOS中从x,y查找对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!