Vertical layout issue with 2 UILabels inside a StackView
Asked Answered
D

1

8

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.

Dap answered 15/11, 2019 at 5:59 Comment(0)
D
11

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
}()
Dap answered 15/11, 2019 at 7:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.