UIStackView
is similar to Android LinearLayout
but I could not figure out how to set weight for the subviews.
Suppose I have a vertical UIStackView
and 3 UIImageView
s in it. I want to set weights 3, 6, 1 consecutively for the UIImageView
s. How do I do that?
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),
])
Intrinsic content size, etc, is totally uninvolved.
Fix the height of the stack view (say, the whole screen)
Put in the three views A, B, C
For A, make an height constraint 0.3 of the height of the stack view
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With