Search code examples
swiftautolayoutuistackviewintrinsic-content-size

UIStackView distribution with intrinsic content size of one subview prioritised


  stackView
+------------+                +
|  topView   | height: 50     |
+------------+                |
|            |                |
|            |                | total height: 300
| bottomView | height: 250    |
|            |                |
|            |                |
+------------+                +

I would like to layout two views (topView and bottomView) in a UIStackView (stackView) with these conditions:

  • stackView has a height (let’s say 300)
  • topView’s and bottomView’s intrinsic content height is the same (let’s say 50)
  • topView’s should be rendered with its intrinsic content height (up to stackView’s height) (so 50)
  • bottomView should take the remaining space (so 250)
  • if topView’s intrinsic content height changes (let’s say to 100) the distribution should be 100/200

None of the distribution modes of UIStackView can cover this.

Setting a constraint with a constant wouldn’t help here, as the intrinsic content height of topView might change.

So I need some Auto Layout features here. I tried setting different content compression resistance priorities and content hugging priorities. Without success, I still feel like they could be a solution (if I knew how to use them correctly).

It doesn’t seem like a complex problem, I can’t find the right Auto Layout API for this. Any hints?


Solution

  • You should set:

    • vertical content hugging priority of top view to be more than bottom view
    • alignment of stack view to fill
    • distribution of stack view to fill

    You should add a width constraint as well, if the top and bottom views do not have intrinsic width.

    Demo:

    enter image description here enter image description here