0
votes

I have two buttons, which I would like to keep centered in their superview as a group.

Expressed in visual format I want something like |-*-[button1]-5-[button2]-*-| where * should be equal and be automatically determined by AutoLayout.

I currently have three workarounds which all seem not very elegant

  1. make the two buttons subviews of a UIView and center that view

  2. calculate the value of * manually and manually update the constraints

  3. align both buttons to the superview's center with an offset manually calculated from the button widths

Any other suggestions?

2

2 Answers

2
votes

I think I was focussing too much on aligning the centers of the two buttons to their superview. When I started thinking about the edges instead I came up with this

[NSLayoutConstraint constraintWithItem:button1
                             attribute:NSLayoutAttributeRight
                             relatedBy:NSLayoutRelationEqual
                                toItem:superview
                             attribute:NSLayoutAttributeCenterX
                            multiplier:1
                              constant:-2.5]];

[NSLayoutConstraint constraintWithItem:button2
                             attribute:NSLayoutAttributeLeft
                             relatedBy:NSLayoutRelationEqual
                                toItem:superview
                             attribute:NSLayoutAttributeCenterX
                            multiplier:1
                              constant:2.5]];

This keeps the two buttons centered in superview with an intermediate spacing of 5.

0
votes

You could center a dummy element, (a hidden view) then offset each button to the left and right.

enter image description here