Stackview里面的其他stackview宽度问题

时间:2018-05-14 13:07:02

标签: ios swift uistackview

我在IB中创建了一个Stackview,它有垂直方向。此stackview与父视图的宽度相等。

现在我以编程方式创建了一个Stackview,例如

let stackViewHorizontal   = UIStackView()
    stackViewHorizontal.axis  = UILayoutConstraintAxis.horizontal
    stackViewHorizontal.distribution  = UIStackViewDistribution.fillEqually
    stackViewHorizontal.alignment = UIStackViewAlignment.leading
    stackViewHorizontal.spacing = 8
    stackViewHorizontal.translatesAutoresizingMaskIntoConstraints = false
    stackViewHorizontal.leadingAnchor.constraint(equalTo: mainStackView.leadingAnchor,constant:0)
    stackViewHorizontal.trailingAnchor.constraint(equalTo: mainStackView.trailingAnchor,constant:0)

这里mainStackView是一个通过IB创建的堆栈视图。而stackviewHorizo​​ntal是以编程方式创建的堆栈视图。 我在stackViewHorizo​​ntal内部的UILabels。我预计这将扩展到全长,每个UiLabel将占据屏幕宽度的50%,因为stackview具有水平轴并且分布是fillEqually。

但我水平地在彼此旁边有一个UiLabels。但没有占据整个屏幕宽度

我做错了请通知?

1 个答案:

答案 0 :(得分:2)

激活约束,同时给它一个高度

stackViewHorizontal.leadingAnchor.constraint(equalTo: mainStackView.leadingAnchor,constant:0).isActive = true
stackViewHorizontal.trailingAnchor.constraint(equalTo: mainStackView.trailingAnchor,constant:0).isActive = true

NSLayoutConstraint.activate([
   stackViewHorizontal.leadingAnchor.constraint(equalTo: mainStackView.leadingAnchor,constant:0), 
   stackViewHorizontal.trailingAnchor.constraint(equalTo: mainStackView.trailingAnchor,constant:0) 
])

//

let stackViewHorizontal   = UIStackView()
stackViewHorizontal.axis  = UILayoutConstraintAxis.horizontal
stackViewHorizontal.distribution  = UIStackViewDistribution.fillEqually
stackViewHorizontal.alignment = UIStackViewAlignment.leading
stackViewHorizontal.spacing = 8
self.view.addSuview(stackViewHorizontal) //// add it here 
stackViewHorizontal.translatesAutoresizingMaskIntoConstraints = false
stackViewHorizontal.leadingAnchor.constraint(equalTo: mainStackView.leadingAnchor,constant:0).isActive = true
stackViewHorizontal.trailingAnchor.constraint(equalTo: mainStackView.trailingAnchor,constant:0).isActive = true