Hardik Vyas
Hardik Vyas

Reputation: 2253

How to detect whether the frames of two UIViews are touching?

I have two UIView objects and I want to check whether any portion of their frames are touching each other.

Such as in the image below:

enter image description here

Upvotes: 2

Views: 480

Answers (2)

OhadM
OhadM

Reputation: 4803

If View 1 goes down vertically then it is easy to tell if they will intersect by checking the .x axis and of course adding the width.

Basically we will check 2 cases, if the View2.x <= View1.x + View1.width <= View2.x + View2.width

Swift example:

let view1TotalWidth = View1.frame.origin.x + View1.frame.size.width
let view2TotalWidth = View2.frame.origin.x + View2.frame.size.width

if View2.frame.origin.x <= view1TotalWidth && view1TotalWidth <= view2TotalWidth {
   print("They will intersect")
}

Now we need to check the 2nd case when the right point (which is what we checked above) is now beyond the view2TotalWidth, which is basically almost the same:

View2.x <= View1.x <= View2.x + View2.width

Again, the answer is under the assumption that view1 will drop down vertically from his current starting position.

Upvotes: 0

Fahri Azimov
Fahri Azimov

Reputation: 11770

You can use CGRect procedures to accomplish what you want. Just check CGRectIntersectsRect( rect1, rect2) where rect1 is the frame of your first view and rect2 is the frame of the second. Good luck!

Upvotes: 2

Related Questions