Search code examples
iosuiviewxibuistackview

Horizontal UIStackView - fix center item's size and stretch other items


I am trying to achieve a layout like this:

enter image description here

Essentially, I need the or label to stay in the middle and occupy a fixed width and the lines to stretch out towards the edges of the screen.

Here's what I did in the XIB:

  • created a horizontal UIStackview, with center alignment.
  • Set the height constraint of the stackview to 20, distribution to fill.
  • added two UIView elements(for the gray lines), with a height constraint set to 5.
  • Added a UILabel between the two UIView elements above.
  • Added more constraints:
  • left UIView leads with 0 from superview and trails with 5 to middle label
  • right UIView leads with 4 from middle label and trails with 0 to superview.

Looks fine on the Interface builder, but on different screen sizes and landscapes, I find the middle "or" label to stretch and kick away the left and right UIViews to make up for the available space, which seems right: enter image description here

If I set a width constraint of 20 on the middle label, the right UIView stretches unevenly like this:

enter image description here

I know the CHP of the elements matters to some extent here, I have even tried setting CHPs like this:

  • CHP of the middle label is 251

  • CHP of left and right UIViews is 250.

This still leaves me with the uneven stretching of right UIView.

What is it that I am doing wrong? Insights much appreciated! Thanks a lot!


Solution

  • Don't set any leading or trailing constraints...

    Set "right view" width constraint equal to "left view" width, and give your stack view a spacing value of 4 or 5.

    Storyboard:

    enter image description here

    Portrait:

    enter image description here

    Landscape:

    enter image description here