2

Why UIStackView resize subviews? I think its work when I set distribution like .fill. But .equalSpacing does not imply such behavior. I'm right?

let stackView = UIStackView()
    stackView.alignment = .firstBaseline
    stackView.axis = .vertical
    stackView.distribution = .equalSpacing
    stackView.spacing = 0.0
    stackView.translatesAutoresizingMaskIntoConstraints = true
    self.view.addSubview(stackView)

    stackView.snp.makeConstraints { (make) -> Void in
      make.top.equalTo(button.snp.bottom)
      make.left.equalTo(view).offset(16.0)
      make.bottom.equalTo(view)
      make.right.equalTo(view).offset(-16.0)
    }

    let exampleView = UIView(frame: .zero)
    stackView.addArrangedSubview(exampleView)
    exampleView.backgroundColor = .yellow

    exampleView.snp.makeConstraints { (make) in
      make.width.equalToSuperview()
      make.height.equalTo(60.0)
    }
  • You shouldn't set `width` and `height` constraints on `exampleView`. Let the `stackview` handle its child. – Kamran Nov 29 '18 at 06:49
  • @Kamran but I want fixed height on subviews – Aleksandr Maybach Nov 29 '18 at 08:12
  • Set that on `stackView`. – Kamran Nov 29 '18 at 08:13
  • @AleksandrMaybach - you want your subviews to have specific heights? OK, but do you want them "spread out" with more spacing between them, to fill the height of the view? e.g. 3 subviews, 60-pts height each, with maybe 100-pts of vertical spacing between them? Or, do you want specific spacing, but not fill the height of the view? e.g. 3 subviews, 60-pts each, with 10-pts vertical spacing, so they only reach down a total of 200-pts? – DonMag Nov 29 '18 at 15:24
  • without "spread out". Not fill, not something. Just pin to top. – Aleksandr Maybach Nov 30 '18 at 09:16

2 Answers2

6

A UIStackView will arrange its subviews.

That means:

  • if you constrain its height (either Height constraint or Top & Bottom constraints), it will size / layout the subviews to fit its Height.
  • if you do not constrain its height, it will use its subview heights for its layout.

enter image description here

DonMag
  • 69,424
  • 5
  • 50
  • 86
1

Please check apple documents about UIStackViewDistributionEqualSpacing

A layout where the stack view positions its arranged views so that they fill the available space along the stack view’s axis. When the arranged views do not fill the stack view, it pads the spacing between the views evenly. If the arranged views do not fit within the stack view, it shrinks the views according to their compression resistance priority. If there is any ambiguity, the stack view shrinks the views based on their index in the arrangedSubviews array.

https://developer.apple.com/documentation/uikit/uistackviewdistribution/uistackviewdistributionequalspacing?language=objc

Cruz
  • 2,602
  • 19
  • 29