Search code examples
iosxcodeuiscrollviewautolayoutuistackview

How to set an empty UIStackView inside a UIScrollView so that i can fill it on runtime?


I'm trying to set an empty vertical UIStackView inside a UIScrollView so that I can fill the UIStackView dynamically on runtime

I tried the solution given by apple here but when I do that, the Auto Layout tool tells me that there is a missing constraint which is either the Y position or the height of the UIStackView. The only difference I have between my UIScrollView and the one from the example is that I don't add a button inside the UIStackView.

When I fill the UIStackView on runtime, the logs say it has to break some constraints and then the UIScrollView fills the screen all the way to the bottom, pushing other views I had there out of sight.

Is this the right way to accomplish what I want? Or is there any other solution?

EDIT:

This is what I have, the logo constraint is only aspect ratio relative to itself

Current status


Solution

  • Set up your constraints as you have them, but without the empty stack view in the scroll view.

    Next:

    • add a UIStackView to the scroll view
    • constrain all 4 sides of the stack view to the scroll view
    • constrain the stack view width equal to the scroll view width
    • constrain the stack view height equal to the scroll view height

    IB should show all constraints satisfied.

    Then - and here's the key - edit the stack view's Height constraint and set it to be a Placeholder:

    enter image description here

    This Height constraint will now be removed at Build-Time. Any elements you add via code as arrangedSubviews will determine the height of the stack view, which will, in turn, define the vertical scrollable area (the .contentSize) --- all handled by auto-layout.