How to set weight in UIStackView in IOS

Intrinsic content size, etc, is totally uninvolved.

To set fractional heights, just set fractional heights:

  1. Fix the height of the stack view (say, the whole screen)

  2. Put in the three views A, B, C

  3. For A, make an height constraint 0.3 of the height of the stack view

  4. For B, make an height constraint 0.6 of the height to the stack view

Set the stack view to distribution:Fill.

If you run this on a powerful iPhone, it will figure out that C is "0.1".

You're done.


UIStackView doesn't have the same concept of weights. It can use a subview's intrinsicContentSize as a weight, but setting a specific intrinsicContentSize typically requires making a subclass and it's used in other situations too (unlike the android:layout_weight attribute you're familiar with, which is only used by LinearLayout).

But since UIStackView works by applying constraints to its arranged subviews, you can get the effect of weights by setting additional constraints between the heights of the subviews. (UIStackView is designed to let you add your own constraints to tweak the layout this way.)

In your case, you want to constrain the height of the top view to be 3 times the height of the bottom view, and you want to constrain the height of the middle view to be 6 times the height of the bottom view.

You can set up a proportional-height constraint in a storyboard by creating an equal-height constraint, then editing the constraint's multiplier.

In code, you could do it like this (on iOS 9.0 or later):

NSLayoutConstraint.activateConstraints([
    top.heightAnchor.constraintEqualToAnchor(bottom.heightAnchor, multiplier: 3),
    middle.heightAnchor.constraintEqualToAnchor(bottom.heightAnchor, multiplier: 6),
])