25

I create UIStackViews programmatically and add them to parent UIStackView, which is created in Storyboard. Child stack views are horizontal with 2 labels. I need to fix width of second UILabel and make the first UILabel fill the rest space.

Now I have this:

Before

And I want this:

After

My code for generating children stack views:

@IBOutlet weak var parentStackView: UIStackView!

func addStackViewsToParentStackView(params: [String: Float]) {
    for (name, value) in params {
        let parameterNameLabel = UILabel() // first label
        parameterNameLabel.text = name
        let parameterValueLabel = UILabel() // second label
        parameterValueLabel.text = value.description
        parameterValueLabel.frame.size.width = 80.0 // I've tried to fix width, but it does't help

        let childStackView = UIStackView(arrangedSubviews: [parameterNameLabel, parameterValueLabel])
        childStackView.axis = .Horizontal
        childStackView.distribution = .FillProportionally
        childStackView.alignment = .Fill
        childStackView.spacing = 5
        childStackView.translatesAutoresizingMaskIntoConstraints = true
        parentStackView.addArrangedSubview(childStackView)
    }
}

Thanks for any help!

Peter Tretyakov
  • 3,380
  • 6
  • 38
  • 54

1 Answers1

58

Just put width constraints on the labels.

parameterValueLabel.widthAnchor.constraint(equalToConstant: 80).isActive = true
Mihir Mehta
  • 13,743
  • 3
  • 64
  • 88
Khanh Nguyen
  • 11,112
  • 10
  • 52
  • 65