如何根据内容动态调整 Swift UIStackView 大小?

How do I make a Swift UIStackView size dynamically based on content?

我已将以下 UIStackView 添加到我的 ViewController。随着视图的改变,textOneLabel 和 textTwoLabel 的值也会改变。

使用以下代码,初始 StackView 居中,各部分按比例填充。但是,对于后续的文本组合,StackView 的边界不会改变,从而使内容偏离中心。如何更改 StackView 属性,使其适应内容并始终居中?

headerStackView.axis = .horizontal
headerStackView.distribution = .fillProportionally
headerStackView.spacing = 8
headerStackView.layer.borderWidth = 1
headerStackView.layer.borderColor = UIColor.red.cgColor
    
headerStackView.translatesAutoresizingMaskIntoConstraints = false
headerStackView.topAnchor.constraint(equalTo: timerHeader.topAnchor, constant: 4).isActive = true
headerStackView.centerXAnchor.constraint(equalTo: timerHeader.centerXAnchor).isActive = true
    
headerStackView.addArrangedSubview(textOneLabel)
headerStackView.addArrangedSubview(textTwoLabel)

首先,忘记你听说过.fillProportionally...

  • 它并不像您想象的那样
  • 如果堆栈视图的间距大于零,您将遇到非常意外的布局问题
  • 如果您的堆栈视图没有宽度(宽度锚点和 leading/trailing 锚点都没有),.fillProportionally 什么都不做

因此,将您的 .distribution 更改为 .fill

添加这些行来控制自动布局对标签的作用:

    textOneLabel.setContentHuggingPriority(.required, for: .horizontal)
    textOneLabel.setContentCompressionResistancePriority(.required, for: .horizontal)

    textTwoLabel.setContentHuggingPriority(.required, for: .horizontal)
    textTwoLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
    

现在,您的 stackView FRAME 将保持居中。