I am trying to detect if two views intersect: a view that's a subview of the main storyboard, and a subview of a subview of the main storyboard.
I tried to use subview1.frame.intersects(subview2.frame)
, and it doesn't work. The function above always returns false
.
As for the context, I'm trying to drag subview1 and drop it onto subview2, and detect the collision between two views upon .Ended
state of PanGesture
.
The view hierarchy can be expressed as the following:
main view
/ \
subview1 view2
\
subview2
Without seeing your view hierarchy I can only guess that it may be that it doesn't work because .intersects compares two rects in the same coordinate space and your views probably have different coordinate spaces (unless they are siblings with the same superview, because .frame is always in your superview's coordinates). UIView has a bunch of convert methods (you want convertRect:fromView) that will transform a point or rect from one view's coordinate space to another. Once you have both rects in the same coordinate space you can use /intersects().
subview1.frame.intersects(subview1.convertRect(subview2.frame, fromView: subview2))
I made it working by using bounds
instead of frame
. So by using subview1.bounds.intersects(subview2.bounds)
, it will return true
when I drop subview1
onto subview2
According to here:
The bounds of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0).
The frame of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within.
I'm not sure why using a CGRect with location and size relative to its own coordinate will work when two UIViews have different parents. If someone can explain furthur I will accept that as an answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With