Swift - Detect if subviews of different superview intersect

ios, swift

Solution

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))

Problem

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 ```

Original source