1

I've been trying to center some buttons in an horizontal UIStackView enter image description here

But doesn't matter what I do, the only not broken layout that I can get is basically: enter image description here

I added constraints to fix the button width programmatically, as the amount of buttons is variable, but can't find a way to fix the spacing between them.

These are the stack view settings:

enter image description here

I tried all the distribution options!

Nuthinking
  • 1,211
  • 2
  • 13
  • 32

1 Answers1

3

The layout in the top image can be achieved as follows:

  1. Add a stack view with default properties (horizontal axis, fill distribution). Add optional spacing as you want.
  2. Constrain the stack view vertically to its superview.
  3. Either don't constrain it horizontally to its superview, or if you want, constrain it using inequality (left >= superview.left, right <= superview.right).
  4. Center your stack view horizontally within its superview.
  5. Add your subviews. Make sure they know how to size themselves (either based on their own contents, or with a fixed width).

The key is the constraints on the UIStackView in 3 & 4. You're horizontally pinning it to its superview, so it needs to figure out how to fill out all the space. Instead, center it horizontally, and allow the stack view only to take up as much space as it needs.

Connor Neville
  • 7,291
  • 4
  • 28
  • 44
  • Note that you may need to adjust content hugging and compression constraints. Should also mention that the same effect in a *vertical* orientation has bitten me more than once, trying to determine why I had too much space between elements in a list. – Michael Long Feb 20 '19 at 21:22
  • @Connor it works but I get errors in the storyboard editor: "need constraints for X position and width". My Stack view has 3 constraints: - Align Center X to: Superview - Bottom Space to: Superview - Height is equal: 82pts Should I add them programmatically? – Nuthinking Feb 20 '19 at 22:13