如何以编程方式设置 setContentHuggingPriority

God*_*her 2 ios autolayout swift

我以编程方式创建视图,但无法开始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
}()
Run Code Online (Sandbox Code Playgroud)

Moj*_*ini 9

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

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

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

label.setContentCompressionResistancePriority(.required, for: .horizontal)
Run Code Online (Sandbox Code Playgroud)