35

Say for example I want to add 3 buttons to a stack view.

Button1 is 200 * 200 (1)

Button2 is 150 * 150 (0.75)

Button3 is 100 * 100 (0.5)

How can I accomplish this in interface builder?

dubbeat
  • 7,706
  • 18
  • 70
  • 122

2 Answers2

75

You can do it in the storyboard using stackview

  1. Add a stackview with Alignment Center and Distribution Fill.
  2. Constraints on stackview is center horizontally and center vertically.
  3. Now add three buttons.
  4. Constraints on button1 is height and width = 200
  5. Constraints on button2 is height and width = 150
  6. Constraints on button3 is height and width = 100

The set up is shown in fig:

enter image description here

You are having conflicts because of Alignment Property which in your case it fill. make is center and its done.

Also we can add spacing between buttons. If we set Distribution Equal Spacing and add height constraint to stackview with height more than height of buttons.

This is vertical stackview. You can test the same with horizontal stackview.

Hope it will work for you.

Irfan
  • 5,070
  • 1
  • 28
  • 32
  • 2
    Works like a charm. The same technique also works for horizontal stack views containing elements which have an unequal size. – SeaWarrior404 Apr 16 '18 at 07:36
  • Alignment doesn't have to be centred, it can be leading or trailing, etc. – sketchyTech Jan 30 '19 at 12:31
  • Surprisingly doesn't work for `UIView's`. I've tried the same approach for `UIView` even I've given same constraint values. Thought when I changed them to `UIButton`. It was working. Can some one suggest how to make the same to work for `UIView`. `Alignment = center` doesn't help either. – Yash Bedi Jun 20 '19 at 13:35
  • @YashBedi Change Distribution property to Fill and Alignment to Center. Time has come to move on from StackView to the new SwiftUI... – Irfan Jun 20 '19 at 16:21
  • 1
    Yep got it working yesterday, before your comment ;-P. Thanks anyways... – Yash Bedi Jun 21 '19 at 08:35
  • @YashBedi... Yes... Actually Fill Proportionally does not make sense, though it was working for UIButtons... – Irfan Jun 21 '19 at 09:09
  • 2
    Doesn't work for UILabels. I want to use dynamic width for label. I have 3 labels on the horizontal axis, want to set the width of left and right label to <= 0.45 multiplier of superview and fill the center label to remaining width – hacker_1989 Mar 21 '21 at 23:30
  • @hacker_1989, did you figure out how to do it with labels? – ScottyBlades Jun 02 '21 at 00:22
0

For those who are looking a solution for UIView, Here it is,

UIStackView ensures that its arranged subviews maintain the same proportion to each another as your layout grows and shrinks. However, unlike the other distribution options, views that are proportional must have an intrinsic content size.

Yash Bedi
  • 1,323
  • 17
  • 25