I have a problem with Cocoa Auto Layout and can't get my head around this problem. All I'd like to achieve is to have two buttons always centered in a view as depicted below.
I've tried lots of different approaches without any success :( please help me out here.
Basically, I have two
UIButtons
inside myUITableViewCell
positioned below that needs to be always centered and with same widths. This is how I made it work in Xcode 7.2. I'm using Swift by the way, if that's in any way related.If you have fixed width buttons and you want fixed distance between two then following steps can do the work :
Width
andHeight
constraint
tobutton1
Example value: 100 height and 100 width.constraint
Equal Widths
andEqual Heights
.Horizontal Spacing
betweenbutton1
andbutton2
. or we can say addLeading Space
tobutton2
frombutton1
. Example value : 150button1
and addconstraint
Horizontally in Container
with -125 value.constrains
likeVertical Spacing to Container
etc as per needed.Example value 125 is equals to (
button1
width
/ 2) + (Horizontal Spacing
/2) which is 100/2 + 150/2 = 125.So adding
Horizontal in Container
to -125 will move thebuttons
to left and that will make this layout center in screen.Example layout and Constraints images attached below :
You can achieved as below way also.
1.Take Leading space for left button, Trailing space for right button.
2.Construct Outlets for both Leading and Trailing constraints.
3.Caluclate constants as below formula.
Hope it will helps you.
Great tips. In my case i wanted the buttons to be centered 10 pixels apart from the center of my view so my math is slightly different
Another trick to do this is to align the right side of
button
to be half the size of the space away from the Center ofsuperview
, and the left side ofbutton2
to be half the size of the space away from the Center ofsuperview
.This only really works if you have a superview that only surrounds the two views you want to centre though.
A neat trick with Auto Layout is to use invisible views as spacers. The constraint system still lays them out as normal. In this case, that space between the two buttons can be an invisible view. You can use the constraints from this constraint string:
Then create a constraint setting
invisibleView.centerX = superview.centerX
.