2016-04-17 72 views
9

我以編程方式創建UIStackView並將它們添加到在Storyboard中創建的父項UIStackView。子堆棧視圖是水平的,有2個標籤。我需要修復第二個UILabel的寬度,並使第一個UILabel填充剩餘空間。修復UIStackView中元素的寬度

現在我有這樣的:

Before

而且我想這一點:

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

感謝您:

After

我產生孩子堆棧視圖代碼幫幫我!

回答

13

只需將寬度約束放在標籤上。

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