以下代码是尝试将UIStackView添加到视图控制器,并以很小的余量固定在所有边缘上,并为其添加标签。
我希望StackView在以后添加更多视图时准备使用.fillProportionally
作为其分发模式。
似乎对于单个布置的子视图,每当使用分配模式为.fillProportionally
和布局边距时,我都会得到一个模棱两可的约束错误(如下所示)。此错误的原因是什么?
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: .zero)
label.text = "ABC"
let stack = UIStackView(arrangedSubviews: [label])
stack.translatesAutoresizingMaskIntoConstraints = false
stack.distribution = .fillProportionally
stack.isLayoutMarginsRelativeArrangement = true
stack.layoutMargins = .init(top: 10, left: 10, bottom: 10, right: 10)
view.addSubview(stack)
NSLayoutConstraint.activate([
stack.centerXAnchor.constraint(equalTo: view.centerXAnchor),
stack.centerYAnchor.constraint(equalTo: view.centerYAnchor),
stack.widthAnchor.constraint(equalTo: view.widthAnchor),
stack.heightAnchor.constraint(equalTo: view.heightAnchor),
])
}
}
模糊约束错误(WTFAutoLayout):
(
"<NSLayoutConstraint:0x600001a432f0 'UISV-canvas-connection' UILayoutGuide:0x6000000f3100'UIViewLayoutMarginsGuide'.leading == UILabel:0x7ff470913280'ABC'.leading (active)>",
"<NSLayoutConstraint:0x600001a423f0 'UISV-canvas-connection' UILayoutGuide:0x6000000f3100'UIViewLayoutMarginsGuide'.trailing == UILabel:0x7ff470913280'ABC'.trailing (active)>",
"<NSLayoutConstraint:0x600001a425d0 'UISV-fill-proportionally' UILabel:0x7ff470913280'ABC'.width == UIStackView:0x7ff46d510030.width (active)>",
"<NSLayoutConstraint:0x600001a77f70 'UIView-leftMargin-guide-constraint' H:|-(10)-[UILayoutGuide:0x6000000f3100'UIViewLayoutMarginsGuide'](LTR) (active, names: '|':UIStackView:0x7ff46d510030 )>",
"<NSLayoutConstraint:0x600001a42940 'UIView-rightMargin-guide-constraint' H:[UILayoutGuide:0x6000000f3100'UIViewLayoutMarginsGuide']-(10)-|(LTR) (active, names: '|':UIStackView:0x7ff46d510030 )>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600001a423f0 'UISV-canvas-connection' UILayoutGuide:0x6000000f3100'UIViewLayoutMarginsGuide'.trailing == UILabel:0x7ff470913280'ABC'.trailing (active)>
首先,将标签的translatesAutoresizingMaskIntoConstraints设置为false。
label.translatesAutoresizingMaskIntoConstraints = false
由于您使用了4个全部的layoutMargins,因此宽度或高度不能等于视图的宽度和高度。
您需要容纳宽度和高度相差20(双面)。
因此约束应该是,
NSLayoutConstraint.activate([
stack.centerXAnchor.constraint(equalTo: view.centerXAnchor),
stack.centerYAnchor.constraint(equalTo: view.centerYAnchor),
stack.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1, constant: -20),
stack.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 1, constant: -20),
])
也请删除以下几行
stack.isLayoutMarginsRelativeArrangement = true
stack.layoutMargins = .init(top: 10, left: 10, bottom: 10, right: 10)