如何以编程方式设置 setContentHuggingPriority

How to set setContentHuggingPriority programmatically

我正在以编程方式创建视图,但无法设置 setContentHuggingPriority 工作。 这是当前结果:

private lazy var stackView: UIStackView = {
    let stackView = UIStackView()
    stackView.axis = .horizontal
    [button, text].forEach(stackView.addArrangedSubview)
    return stackView
}()

private lazy var button: UIButton = {
    let button = UIButton()
    button.setImage(Asset.configIcon.image, for: .normal)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setContentHuggingPriority(.defaultHigh, for: .horizontal)
    button.backgroundColor = .red
    return button
}()

private lazy var text: UILabel = {
    let label = UILabel()
    label.text = "This line should have more width than the button"
    label.numberOfLines = 0
    label.translatesAutoresizingMaskIntoConstraints = false
    label.setContentHuggingPriority(.defaultLow, for: .horizontal)
    return label
}()

您正在寻找按钮适合其内容的状态,然后标签占据任何左侧 space 并用多行文本填充它。

因为您使用的是多行标签,所以您也应该为两者都设置 contentCompressionResistancePriority:

button.setContentCompressionResistancePriority(.required, for: .horizontal)

label.setContentCompressionResistancePriority(.required, for: .horizontal)