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:
I want the red label to hug the content and never compress. I add this:
label1.setContentHuggingPriority(.defaultHigh, for: .horizontal)
Looks good so far but when the text is too long in the blue label I get this:
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
defaultHigh
is not enough priority in this case. Set it to required
instead.
label1.setContentHuggingPriority(.required, for: .horizontal)
label1.setContentCompressionResistancePriority(.required, for: .horizontal)