Why UIStackView resize arranged subviews?

6.2k Views Asked by At

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)
    }
2

There are 2 best solutions below

0
On BEST ANSWER

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

0
On

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