Search code examples
iosswiftnslayoutconstraintstackview

Stack View Distribution with Dynamic Label Width


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

Solution

  • 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.