Detect if UIView crosses other UIViews

I have a bunch of UIView on the screen. I would like to know that it is best to check if a particular view (to which I have a link) is the intersection of ANY other views. The way I do it right now is repeated, although all the sub-items are checked one by one if there is an intersection between frames.

It does not seem very effective. Is there a better way to do this?

+4
source share
3 answers

First, create some array that stores the frames of all your UIView and their associated links.

Then, potentially in the background thread, you can run some collision testing using what's in the array. For some simple collision testing only for rectangles check this SO question: Simple collision algorithm for rectangles

Hope this helps!

0
source

There is a CGRectIntersectsRect function that takes two CGR addresses as arguments and returns if the two specified rectangles intersect. And UIView has a subviews property, which is an NSArray of UIView objects. Thus, you can write a method with a return value of BOOL that will go through this array and check if two rectangles intersect, for example:

- (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; } 
+34
source

To achieve the same in quick accordance with the accepted answer, here is the function. Ready code. Just copy and use it according to the steps. By the way, I am using Xcode 7.2 with Swift 2.1.1.

 func checkViewIsInterSecting(viewToCheck: UIView) -> Bool{ let allSubViews = self.view!.subviews //Creating an array of all the subviews present in the superview. for viewS in allSubViews{ //Running the loop through the subviews array if (!(viewToCheck .isEqual(viewS))){ //Checking the view is equal to view to check or not if(CGRectIntersectsRect(viewToCheck.frame, viewS.frame)){ //Checking the view is intersecting with other or not return true //If intersected then return true } } } return false //If not intersected then return false } 

Now call this function according to the following -

 let viewInterSected = self.checkViewIsInterSecting(newTwoPersonTable) //It will give the bool value as true/false. Now use this as per your need 

Thanks.

Hope this helps.

+2
source

All Articles