Alessandro
Alessandro

Reputation: 4110

Detect if UIbuttons overlap

I have two UIButtons on my view, and I am trying to detect if the two overlap, in oder to do:

if (overlap) move the second button

I have tried this:

if (BluetoothDeviceButton.X1 < btn.X2 && BluetoothDeviceButton.X2 > btn.X1 &&
    BluetoothDeviceButton.Y1 < btn.Y2 && BluetoothDeviceButton.Y2 > btn.Y1){

 }

I can't really get what I should put instead of X1, X2, etc. And I don't really know if this method is going to work at all.

Upvotes: 0

Views: 490

Answers (4)

HereTrix
HereTrix

Reputation: 1417

Use BluetoothDeviceButton.frame.origin.x. Frame property contain also size.

Upvotes: 0

Schrodingrrr
Schrodingrrr

Reputation: 4271

Firstly make sure they are in the same view. If not, then get their frames using convertRectToView, or converRectFromView. Then use the CGRectContainsPoint of the CGGeometry class and check if any corner of one button lies in the frame of the other button.

PS. your corners will be:

CGFloat x1 = button1.frame.origin.x;
CGFloat y1 = button1.frame.origin.y;
CGFloat x2 = button1.frame.origin.x + button1.frame.size.width;
CGFloat y2 = button1.frame.origin.y + button1.frame.size.height;

Your corners will be:

CGPoint topLeft = CGPointMake(x1,y1);
CGPoint topRight = CGPointMake(x2,y1);
CGPoint bottomLeft = CGPointMake(x1,y2);
CGPoint bottomRight = CGPointMake(x2,y2);

This is just one possible solution. This is just to help understand geometry.

But the simplest solution would be using CGRectIntersectsRect (button1.frame, button2.frame);

Upvotes: 0

Tarek Hallak
Tarek Hallak

Reputation: 18470

You need to use BluetoothDeviceButton.frame.origin.x or BluetoothDeviceButton.center.x.

Upvotes: 0

Joel
Joel

Reputation: 16134

CGRectIntersectsRect(CGRect rect1, CGRect rect2) will tell you if their frames overlap.

if (CGRectIntersectsRect(btn.frame, BluetoothDeviceButton.frame)) {
   ...
}

Upvotes: 6

Related Questions