Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 views. The way I am doing it right now is, iterating though all the subviews and check one by one if there's an intersection between the frames.

This doesn't seem very efficient. Is there a better way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
602 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...