Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set weight in UIStackView in IOS

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 UIImageViews in it. I want to set weights 3, 6, 1 consecutively for the UIImageViews. How do I do that?

layout diagram

like image 292
Asim Roy Avatar asked Dec 08 '15 16:12

Asim Roy


2 Answers

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),
])
like image 188
rob mayoff Avatar answered Oct 07 '22 10:10

rob mayoff


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.

like image 42
Fattie Avatar answered Oct 07 '22 10:10

Fattie