3

How can programmatically check if 2 objects are overlapping on my UIViewController? I am using this method to randomly move the objects around the UIView.

CGFloat x = (CGFloat) (arc4random() % (int) self.container.bounds.size.width);
CGFloat y = (CGFloat) (arc4random() % (int) self.container.bounds.size.height);

CGPoint squarePostion = CGPointMake(x, y);
_button.center = squarePostion;

I have 3 objects I am moving around using this fragment of code. Sometimes they overlap each other, which is a problem. Is there anyway I can check if the objects are overlapping each other before I make them visible?
Thanks guys!

Larme
  • 24,190
  • 6
  • 51
  • 81
Stephen Bennett
  • 431
  • 6
  • 17
  • Have a look http://stackoverflow.com/questions/23247919/check-if-cgrect-is-contained-within-another-transformed-rect – svrushal May 19 '14 at 13:55

1 Answers1

4

You can use CGRectIntersectsRect to check if two views' frames are intersecting.

You would do it like this:

if(CGRectIntersectsRect(view1.frame, view2.frame)) {
  //The two views are "overlapping"
}

Find more information here: https://developer.apple.com/library/ios/documentation/graphicsimaging/reference/CGGeometry/Reference/reference.html#//apple_ref/c/func/CGRectIntersectsRect

KerrM
  • 5,139
  • 3
  • 35
  • 60