2

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

Community
  • 1
  • 1
Hardik Vyas
  • 1,973
  • 1
  • 20
  • 43
  • have a look at http://stackoverflow.com/questions/4874288/use-key-value-observing-to-get-a-kvo-callback-on-a-uiviews-frame – Ravi Jan 19 '16 at 10:14
  • Hmm... it sounds like you should probably be using UIDynamics (or maybe even SpriteKit). What is it you're actually trying to do once they touch? – Fogmeister Jan 19 '16 at 13:08
  • just want to display a msg that they touched... – Hardik Vyas Jan 20 '16 at 04:59

2 Answers2

2

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!

Fahri Azimov
  • 11,470
  • 2
  • 21
  • 29
0

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.

OhadM
  • 4,687
  • 1
  • 47
  • 57