ios 修复 UIStackView 中元素的宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36675758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:55:28  来源:igfitidea点击:

Fix width of element in UIStackView

iosswiftuistackview

提问by Peter Tretyakov

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 UILabeland make the first UILabelfill the rest space.

UIStackView以编程方式创建s 并将它们添加到UIStackView在 Storyboard 中创建的parent 。子堆栈视图是水平的,带有 2 个标签。我需要固定第二个的宽度UILabel并使第一个UILabel填充其余空间。

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!

谢谢你的帮助!

回答by Khanh Nguyen

Just put width constraints on the labels.

只需在标签上设置宽度限制即可。

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