How to add Equal Spacing and equal width for button in iOS Auto layout
With iOS 9 and Xcode 7, you can now have the expected result with
UIStackView and only 3 or 4 auto layout constraints.
The following step by step uses Storyboard.
- Create 6
UIButtons and 5
UIViews. Align them horizontally. Give some color to your views.
- Select all your views and buttons and click on the
Stackbutton. You will have all your buttons and colored views aligned in a
- Select your stack view, go to the
Utilitiespanel and select the
Attributes Inspectoritem. There, click on the
Distributionbutton and select "Fill Equally".
- For now, your stack view's height relies on your buttons intrinsic content size. If you're fine with it, you can go to step 5. However, if needed, you can give your stack view a height constraint. Select your stack view, click on the
Pinbutton, check the
Heightbutton, add the required value and click on the
Add 1 Constraintbutton.
As an alternative, If you want each element of your stack view to have its height matching its width, select the first button of your stack view, click on the
Pin button, select
Aspect Ratio and click on the
Add 1 Constraint button.
You can check that your aspect ratio constraint is correct in your
Document outline (left panel) and, if you need, you can change it with a different constraint in the
Attribute inspector (right panel).
- Now, it's time to give some external constraints to your stack view. Select your stack view. Click on the
pinbutton, make sure the
Constrain to marginbutton is not select and set leading, trailing and bottom constraints to zero. Make sure that the bottom constraint is related to your view controller's view. Then, change the
Update Framesbutton to "All Frames in Container". You can now click on the
Add 3 Constraintsbutton.
Your stack view is now set.
If you don't need your colored views width to match your buttons width, you can build a stack view with only
UIButtons and simply add spacing to your stack view in the
Attribute inspector. However, you will have to find a way to add a background color behind your stack view. Apple states about it in the UIKit Framework Reference:
The UIStackView is a nonrendering subclass of UIView. It does not provide any user interface of its own. Instead, it just manages the position and size of its arranged views. As a result, some properties (like backgroundColor) have no affect on the stack view.
I've build a Xcode project with 4 different stack views:
- one with colored views and relying on the embedded
UIButtons intrinsic content size for its height,
- one with colored views and with a
UIButton"equal width and height" constraint,
- one with colored views and with its own height constraint,
- one without colored views but with spacing and embedded inside a colored view.
You can find this project on this GitHub repo.