Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for overlapping objects on ViewController

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!

like image 732
Stephen Bennett Avatar asked Aug 14 '26 22:08

Stephen Bennett


1 Answers

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

like image 152
KerrM Avatar answered Aug 16 '26 23:08

KerrM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!