David Webb
David Webb

Reputation: 139

Changing the height of items in UIStackView based on Screen height

I am using UIStackViews in the latest Xcode, the layout is as listed below:

Text label
Picker (1 Component)
Text label
Picker (1 Component)
Text Label
Picker (4 Components)
Segmented Control (3 Sections)

I have the following UI constraints:

StackViewTop = SafeAreaTop + 8
StackViewLeading = SafeAreaLeading + 8
StackViewTrailing = SafeAreaTrailing - 8
Picker_1 = 96px
Picker_2 = Picker_1 Height
Picker_3 = Picker_2 Height

Using the intrinsic sizes for the components (other then the 3 pickers which I set to 96px) everything fits on an iPhone SE (568px) however the pickers are rather short. On any other device there is more vertical space to make the pickers taller.

I would like to have the three pickers increase their height up to a their intrinsic height when there is vertical space available; I can not find the right combinations of settings in Interface Builder to make this work. Is there a way to do this?

A second part of this questions is that I would like the width of the stack view to be limited (to maybe 512) and centered if the screen is wide enough.

Upvotes: 0

Views: 3235

Answers (1)

Kamil Szostakowski
Kamil Szostakowski

Reputation: 2163

When it comes to the first part of your question.

This is how you should configure your stack view. In addition to what you have done, I would add a bottom constraint with greater than or equal sign. It won't let the stack view growing out of bounds.

StackView configuration

Update

After taking a look at your layout I changed the solution a little bit.

  • The heights equality for the pickers is configured the same way you did.
  • The top picker has a height constraint greater or equal 96. It will let the auto layout engine to increase it's size if there is enough space.
  • All the labels and a segment control have a vertical content compression resistance priority set to 1000 (required).
  • The top picker has a vertical content compression resistance priority set to 250 (low).

You can find my implementation in this GitHub repository.
Here is the result.

enter image description here

Upvotes: 1

Related Questions