Search code examples
iosswiftuilabel

Trouble settings content hugging and compression for labels in UIStackView


I am having issues getting my head around content compression and resistance on labels. Consider:

let label1 = UILabel()
label1.text = "hello"
label1.textColor = .white
label1.backgroundColor = .red

let label2 = UILabel()
label2.text = "bye"
label2.textColor = .white
label2.backgroundColor = .blue

These labels are in a horizontal stack view.

let stackView = UIStackView(arrangedSubviews: [label1, label2])

This gives the following:

enter image description here

I want the red label to hug the content and never compress. I add this:

label1.setContentHuggingPriority(.defaultHigh, for: .horizontal)

enter image description here

Looks good so far but when the text is too long in the blue label I get this:

enter image description here

I tried setting label1.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) but it makes no difference.

What am I doing wrong here? Would love some advice on how to fix this.

Thanks


Solution

  • defaultHigh is not enough priority in this case. Set it to required instead.

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

    enter image description here