修复UIStackView中元素的宽度

时间:2016-04-17 11:14:31

标签: ios swift uistackview

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

现在我有了这个:

Before

我想要这个:

After

我生成子堆栈视图的代码:

@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)
    }
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:34)

只需在标签上加上宽度限制。

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