Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical layout issue with 2 UILabels inside a StackView

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.

like image 339
DesperateLearner Avatar asked Nov 15 '19 05:11

DesperateLearner


1 Answers

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
}()
like image 190
DesperateLearner Avatar answered Nov 15 '22 12:11

DesperateLearner