我有一个带有两个控件的堆栈视图。
当 UI 不受垂直约束时: Vertical1
当 UI 被垂直约束时:Horizontal1
我得到了如图所示的两个 UI。第一次显示 UI 时没有约束冲突。但是,当我从垂直约束变为垂直 = 常规时,我会遇到约束冲突。
当我注释掉 stackview 空间时(参见下面的代码注释),我没有遇到约束冲突。
class ViewController: UIViewController {
var rootStack: UIStackView!
var aggregateStack: UIStackView!
var field1: UITextField!
var field2: UITextField!
var f1f2TrailTrail: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
createIntializeViews()
createInitializeAddStacks()
}
private func createIntializeViews() {
field1 = UITextField()
field2 = UITextField()
field1.text = "test 1"
field2.text = "test 2"
}
private func createInitializeAddStacks() {
rootStack = UIStackView()
aggregateStack = UIStackView()
// If I comment out the following, there are no constraint conflicts
aggregateStack.spacing = 2
aggregateStack.addArrangedSubview(field1)
aggregateStack.addArrangedSubview(field2)
rootStack.addArrangedSubview(aggregateStack)
view.addSubview(rootStack)
rootStack.translatesAutoresizingMaskIntoConstraints = false
aggregateStack.translatesAutoresizingMaskIntoConstraints = false
field1.translatesAutoresizingMaskIntoConstraints = false
field2.translatesAutoresizingMaskIntoConstraints = false
f1f2TrailTrail = field2.trailingAnchor.constraint(equalTo: field1.trailingAnchor)
}
override public func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if traitCollection.verticalSizeClass == .regular {
aggregateStack.axis = .vertical
f1f2TrailTrail.isActive = true
} else if traitCollection.verticalSizeClass == .compact {
f1f2TrailTrail.isActive = false
aggregateStack.axis = .horizontal
} else {
print("Unexpected")
}
}
}
约束冲突在这里 -
(
"<NSLayoutConstraint:0x600001e7d1d0 UITextField:0x7f80b2035000.trailing == UITextField:0x7f80b201d000.trailing (active)>",
"<NSLayoutConstraint:0x600001e42800 'UISV-spacing' H:[UITextField:0x7f80b201d000]-(2)-[UITextField:0x7f80b2035000] (active)>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600001e42800 'UISV-spacing' H:[UITextField:0x7f80b201d000]-(2)-[UITextField:0x7f80b2035000] (active)>
当我将输出放在 www.wtfautolayout.com 中时,我得到以下信息: 更容易阅读输出
上图中显示的第二个约束让我认为在评估约束之前没有发生对 stackview 垂直轴的更改。
谁能告诉我我做错了什么或如何正确设置它(最好没有故事板)?
[编辑] 文本字段的后沿对齐以具有此: