Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set setContentHuggingPriority programmatically

Im creating a view programmatically, but i can't set setContentHuggingPriority to work. This is the current result:

the red space should be equals the button

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
}()
like image 806
Godfather Avatar asked Feb 07 '26 09:02

Godfather


1 Answers

You are looking for the state that the button fits it's content and then the label takes any left space and fill it with multiline text.

Because you are using multiline label, You should set contentCompressionResistancePriority for both as well:

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

label.setContentCompressionResistancePriority(.required, for: .horizontal)
like image 170
Mojtaba Hosseini Avatar answered Feb 08 '26 23:02

Mojtaba Hosseini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!