4

I have a UIStackView however, the first view of the subViews is a UILabel and it is not sizing it accordingly.

My code is as per below;

private let stackView: UIStackView = {
    let view = UIStackView()
    view.translatesAutoresizingMaskIntoConstraints = false
    view.axis = .horizontal
    view.distribution = .fillProportionally
    view.alignment = .trailing
    view.spacing = 8
    return view
}()

and I, of course, add my subViews within init as below;

    stackView.addArrangedSubview(currentBidLabel)
    stackView.addArrangedSubview(seperator)
    stackView.addArrangedSubview(adCreatedAtLabel)
    stackView.addArrangedSubview(moreButton)

My current result is as per the illustration below;

illustration

The result I'm looking for is the following;

  1. Red = Dynamic Label Width (same as Blue)
  2. Green = Fixed Width
  3. Blue = Fill Remaining Space
  4. Cyan = Fixed Width
David Henry
  • 1,972
  • 20
  • 43
  • **horizontal** stack view doesn't fit with `.trailing` alignment. Instead you should be using `.fill`/`.top`/`.center`/`.bottom`. Do you need the **AED 400** and **1d ago** both labels occupy the same width? – nayem Dec 20 '19 at 07:30
  • When I do fill Proportionally, I get the views smashed up into 0 width... – ScottyBlades Jun 02 '21 at 00:25

1 Answers1

8

You should set the desired ContentHuggingPriority for each label. The following setup will be matched to your needs

redLabel.setContentHuggingPriority(. required, for: .horizontal)
greenLabel.setContentHuggingPriority(.required, for: .horizontal)
blueLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
cyanLabel.setContentHuggingPriority(.required, for: .horizontal)
  • defaultLow means to fill the rest.
  • required means fit first.

And other values should be between these two.

Sumit
  • 41
  • 5
Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278