Search code examples
iosautolayoutuistackview

Fill Proportionally in UIStackView


I am using Storyboard to create a layout which consists of a UITableView and a UIView at the bottom. I am using UIStackView and playing them vertically. I want the UITableView to take 80% of the height and UIView (footer) to take 20%. I am using Fill Proportionally option of UIStackView and even through in Xcode preview it looks good but when the app is run it does not render correctly. Here is what I want it to look like:

enter image description here

And here is what it looks like when it is run:

enter image description here

Ideas?


Solution

  • You will need to set an explicit constraint to make tableView.height 4x bigger than your view size. They don't have intrinsic content size, so the stackView does not "know" how to properly fill the space.

    Also, set the distribution mode to .fill, because .fillProportionally uses intrinsic content size to determine proper distribution (excerpt from docs):

    case fillProportionally

    A layout where the stack view resizes its arranged views so that they fill the available space along the stack view’s axis. Views are resized proportionally based on their intrinsic content size along the stack view’s axis.

    Using constraints we are setting the size explicitly, not using intrinsic content size - thus .fillProportionally does not work. I assume in that case the stackView uses values returned by view.intrinsicContentSize directly. However, constraints will not change view.intrinsicContentSize.

    If you would be doing it in code, you could do it with this:

    tableView.heightAnchor.constraint(equalTo: myView.heightAnchor, multiplier: 4).isActive = true
    

    In storyboards, control drag from tableView to the myView and select Equal Heights:

    enter image description here

    Then select the created constraint and set the appropriate multiplier:

    enter image description here