Search code examples
iosswiftautolayoutuistackview

Why are subviews not visible when I set UIStackView distribution to equalspacing?


I want to put a group of custom views inside a UIStackView horizontally. Each of the subviews has a width and height equal to constant constraint:

 let stack = UIStackView(frame: frameRect)
 stack.axis = UILayoutConstraintAxis.horizontal
 stack.distribution = UIStackViewDistribution.equalSpacing
        
 stack.layoutMargins = UIEdgeInsets(top: 0, left: 40, bottom: 0, right: 40)
 stack.isLayoutMarginsRelativeArrangement = true

 for i in 1...3 {
     let numberView = RotatingNumberView()
     numberView.heightAnchor.constraint(equalToConstant: CGFloat(cellSize))
     numberView.widthAnchor.constraint(equalToConstant: CGFloat(cellSize))
     numberViews.append(numberView)
     stack.addArrangedSubview(numberView)
  }

If I change to fillEqually distribution, the subviews are shown, but their widths are stretched to fill the stackView.

I guess it has something to do with hugging or compression resistence priority, but setting these in subview doesn't work.

What is happening here?


Solution

  • For all distributions except the fillEqually, the stack view uses each arranged view’s intrinsicContentSize property when calculating its size along the stack’s axis.

    So overriding this property will work.

      override var intrinsicContentSize: CGSize { return CGSize(your values) }