Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: check if view touches another view

I animate a lot of views using (..) [UIView commitAnimations]. Now i want to check if the view, which was "shot", has touched another view. Does anyone know how to implement this? Maybe if(view.frame.origin.x==anotherview.frame.origin.x){ } ..

like image 326
Smoothie Avatar asked Dec 18 '11 16:12

Smoothie


2 Answers

Conceptually, a view "touches" another view if their bounding rects intersect. So to compare the bounding rects of two views, you want to do something like:

Boolean viewsOverlap = CGRectIntersectsRect(viewA.bounds, viewB.bounds);

But that alone won't work because the bounding rects of the views are specified in their own coordinate spaces (meaning both start at 0,0, etc. etc.) So you also need to transform the rects to a common coordinate space before you compare them:

CGRect boundsA = [viewA convertRect:viewA.bounds toView:nil];
CGRect boundsB = [viewB convertRect:viewB.bounds toView:nil];
Boolean viewsOverlap = CGRectIntersectsRect(boundsA, boundsB);

From there, you should be able to figure out how to iterate efficiently through your list of views-you-care-about to determine if any overlap.

like image 192
Jonathan Grynspan Avatar answered Nov 06 '22 21:11

Jonathan Grynspan


Alternatively you could just compare the frames if they're in the same superview:

BOOL methodB = CGRectIntersectsRect(viewA.frame, viewB.frame);
like image 25
user2851943 Avatar answered Nov 06 '22 23:11

user2851943