Keep UIButtons centered using autolayout in storyb

2019-04-28 08:14发布

问题:

I have two buttons contained within a view (to be precise, a UITableView footer):

I would like to keep the buttons centered (with the gap in-between) regardless of the width of the superview (which will increase, for example, if the device is rotated to portrait orientation).

Is there a way to define these autolayout constraints purely in the storyboard, or will I need to use NSLayoutConstraints in code?

回答1:

You can achieve that by adding a constraint for each button to align the leading/trailing to the center of the container view, plus some separation between them.

How to do it:

  • For the left side button, add a constraint between the button and superview to center it horizontally.

  • Edit the constraint and change the "Second Item" attribute to be button1.trailing, and set a constant of 10 (or whatever distance you want between the right border of the button and the center of the screen).

  • For the right side button, add a constraint between the button and superview to center it horizontally.

  • Edit the constraint and change the "Second Item" attribute to be button2.leading and set a constant of -10 (or whatever distance you want between the left border of the button and the center of the screen).