1

I have a vertical stack view which can contain 1-3 subviews. The subviews should have height about 1/3 of stack view height, even when there's only one or two of them.

enter image description here

I tried adding:

view.heightAnchor.constraint(equalTo: stack.heightAnchor, multiplier: 0.3)

but it throws a constraint conflict, because stack view pins a subview to top and bottom.

Is there a way to do this with UIStackView?

vortek
  • 474
  • 2
  • 14

1 Answers1

1

You can accomplish this pretty easily with one stack view nested inside another, using the right setting for each and constraining the orange subviews (which are children of the inner stack view) to the height of the outer stack view. Here is a diagram that shows the setup, and the necessary stack view attributes:

enter image description here

Daniel Hall
  • 13,457
  • 4
  • 41
  • 37
  • 1
    that is one awesome diagram, thank you! I'm wondering how you thought of that and whether there's a general principle at work here? I haven't used stack views much, bc I've been supporting iOS 8. – vortek Dec 29 '17 at 03:48
  • 1
    I just have a lot of practice banging my head against stack views and auto layout :) Nesting stack views is definitely a common / encouraged solution for a lot of spacing and alignment scenarios. Here is a good demonstration of it from Apple: https://developer.apple.com/videos/play/wwdc2015/218/ – Daniel Hall Dec 29 '17 at 04:03