简体   繁体   中英

Fix width of element in UIStackView

I create UIStackView s 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:

之前

And I want this:

后

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!

只需在标签上加上宽度约束即可。

parameterValueLabel.widthAnchor.constraint(equalToConstant: 80).isActive = true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM