xcodeuistackview

How can I set the height of a horizontal stackview in Xcode 15?


I'm new to iOS development and I'm having issues with using stack views that doesn't seem to be an issue with earlier versions of Xcode or perhaps it's my process. If i have 4 objects on the screen and I embed them in a horizontal stack view, it shrinks all the objects to some size of it's own choosing and while I can change the width and set it to fill equally, that just spaces out the objects rather than stretching them and there is no way to set the height. What's going on?

I was expecting the stack view to remain the size it started as and the objects simply be embedded in it. I expect to be able to resize an object inside of a stack view if needed. i expect to be able to set the height of the stack view. What actually happens is as soon as the objects are embedded in the stackview, the whole thing resizes to a tiny fraction of the original size and but the height attribute of the stack view is greyed out. original size of the objects horizontal stack view


Solution

  • A UIStackView arranges its subviews based on subview intrinsic content sizes, subview size constraints, stack view alignment and distribution properties, constraints set on the stack view itself, etc.

    Which constraints to set and which properties to set will depend on your ultimate layout goal.

    For example, looking at your first screen shot (I'll assume these are 4 buttons), what should happen when the device is rotated?

    Keep the buttons the same size and same spacing, centered horizontally:

    enter image description here

    Keep the leading and trailing the same, and spread the buttons out:

    enter image description here

    Keep the leading and trailing the same, keep the spacing the same, keep the buttons 1:1 ratio... and scale the items to fit the width:

    enter image description here

    In your question, you only described what you see happening ... not what you want to happen, so let's just start simple...

    We want:

    Here's what we'll have for constraints:

    enter image description here

    So...

    And we set these properties on the stack view:

    enter image description here

    UIStackView is a very powerful layout tool. The best way to understand it is to work with it. Head over to Google (or your favorite search engine) and search for UIStackView tutorial ... you'll get many, many results.