I have a title label as defined below:
private lazy var titleLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 2
label.setContentCompressionResistancePriority(.init(rawValue: 999), for: .vertical)
return label
}()
private lazy var descriptionLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byTruncatingTail
return label
}()
titleLabel can grow and force to shrink the descriptionLabel.
The cell is height is fixed to 120 or 78. When the cell height is 78, the descriptionLabel height is 0
Both are added to a UIStackview
private lazy var labelStackView: UIStackView = {
let stackView = UIStackView()
stackView.addArrangedSubview(titleLabel)
stackView.addArrangedSubview(descriptionLabel)
stackView.axis = .vertical
stackView.distribution = .fill
return stackView
}()
The stackView is added inside the containerView with padding to the top, left, right & bottom. The containerView is pinned to the edges of the contentView.
The distribution on the stackView is set to fill to allow descriptionLabel to shrink. This set up causes the constraint to break.
Issue
titleLabel - Height is ambiguous for UILabel
descriptionLabel - Height and vertical position are ambiguous for UILabel
Is there a way to achieve this without breaking the constraint?
I tried setting content resistance priority for both labels as follows:
titleLabel -> label.setContentCompressionResistancePriority(.init(rawValue: 999), for: .vertical)
descriptionLabel -> label.setContentCompressionResistancePriority(.init(rawValue: 998), for: .vertical)
I still had no luck.
By setting a content hugging priority on the descriptionLabel, I was able to fix the layout ambiguity.
private lazy var descriptionLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byTruncatingTail
label.setContentHuggingPriority(.high, for: .vertical)
return label
}()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With