Detecting if UIView is intersecting other UIViews

前端 未结 4 988
谎友^
谎友^ 2020-12-03 09:35

I have a bunch of UIViews on the screen. I would like to know what\'s the best to way to check if a particular view (which I have reference to) is intersection ANY other vie

4条回答
  •  醉梦人生
    2020-12-03 09:45

    There's a function called CGRectIntersectsRect which receives two CGRects as arguments and returns if the two given rects do intersect. And UIView has subviews property which is an NSArray of UIView objects. So you can write a method with BOOL return value that'll iterate through this array and check if two rectangles intersect, like such:

    - (BOOL)viewIntersectsWithAnotherView:(UIView*)selectedView {
    
        NSArray *subViewsInView = [self.view subviews];// I assume self is a subclass
                                           // of UIViewController but the view can be
                                           //any UIView that'd act as a container 
                                           //for all other views.
    
         for(UIView *theView in subViewsInView) {
    
           if (![selectedView isEqual:theView])
               if(CGRectIntersectsRect(selectedView.frame, theView.frame))  
                  return YES;
        }
    
      return NO;
    }
    

提交回复
热议问题