FInd the object from x,y in iOS

2019-08-04 17:51发布

问题:

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;
      }