为什么UIButton需要约束才能出现在UIStackView中

时间:2017-12-14 11:01:30

标签: ios uibutton autolayout uistackview

鉴于以下Playground代码,我希望我的两个按钮可以填满整个StackView。

l = [(x, data.copy()) for x in range(20, 24)]

但是没有一个出现!但是,如果我向任一按钮添加1px的宽度约束,则两个按钮都按预期布局。

import UIKit

let button = UIButton(type: .custom)
button.setTitle("My Button", for: .normal)
button.backgroundColor = .purple

let anotherButton = UIButton(type: .custom)
anotherButton.setTitle("Another Button", for: .normal)
anotherButton.backgroundColor = .orange

var stackView: UIStackView = UIStackView(frame: CGRect(x: 0.0, y: 0.0, width: 300, height: 300))
stackView.axis = .vertical
stackView.spacing = 10.0
stackView.distribution = .fillEqually
stackView.alignment = .fill

stackView.addArrangedSubview(button)
stackView.addArrangedSubview(anotherButton)
stackView

我很困惑!为什么这个单一约束会产生影响?我应该做一些其他事情,而不是添加“虚拟约束”,以强制按钮正确布局吗?

1 个答案:

答案 0 :(得分:0)

它可能是游乐场中的一个错误,但这在app中与我合作,没有任何 widthAnchor 约束

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let button = UIButton(type: .custom)
    button.setTitle("My Button", for: .normal)
    button.backgroundColor = .purple



    let anotherButton = UIButton(type: .custom)
    anotherButton.setTitle("Another Button", for: .normal)
    anotherButton.backgroundColor = .orange

    var stackView: UIStackView = UIStackView(frame: CGRect(x: 0.0, y: 100.0, width: 300, height: 300))
    stackView.axis = .vertical
    stackView.spacing = 10.0
    stackView.distribution = .fillEqually
    stackView.alignment = .fill

    stackView.addArrangedSubview(button)
    stackView.addArrangedSubview(anotherButton)

    self.view.addSubview(stackView)
}

enter image description here