Detecting if UIView is intersecting other UIViews

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

Leave a Comment