【发布时间】:2017-02-24 23:34:45
【问题描述】:
我正在使用 Swift 3、iOS 10、XCode 8.2。
在我的代码中,我需要以编程方式创建一个UIViewController,因此也需要以编程方式指定其布局和内容。
@IBAction func testViewController() {
let detailViewController = UIViewController()
detailViewController.view.backgroundColor = UIColor.white
let titleLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.blue
label.text = "Scan Results"
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 18)
label.textColor = UIColor.white
return label
}()
let titleConstraints: [NSLayoutConstraint] = [
NSLayoutConstraint(item: titleLabel, attribute: .left, relatedBy: .equal, toItem: self.view, attribute: .left, multiplier: 1, constant: 0),
NSLayoutConstraint(item: titleLabel, attribute: .right, relatedBy: .equal, toItem: self.view, attribute: .right, multiplier: 1, constant: 0),
NSLayoutConstraint(item: titleLabel, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 40)
]
detailViewController.view.addSubview(titleLabel)
detailViewController.view.addConstraints(titleConstraints)
self.navigationController?.pushViewController(detailViewController, animated: true)
}
在垂直视图中(忽略所有其他垃圾;只关注蓝色标题栏):
但在水平视图中:
设置的正确约束是什么,以便它占据栏的整个宽度,并且由于状态栏在水平时消失,因此顶部没有多余的空间?
编辑
在提出@thexande 建议后,我确实收到了一个错误:
[LayoutConstraints] 视图层次结构没有为 约束:
<NSLayoutConstraint:0x608000098100 UILabel:0x7fe35b60edc0'Scan Results'.left == UIView:0x7fe35b405c20.left (inactive)>添加到视图时, 约束的项目必须是该视图的后代(或视图 本身)。如果之前需要解决约束,这将崩溃 视图层次结构已组装。打断 -[UIView(UIConstraintBasedLayout) _viewHierarchyUnpreparedForConstraint:] 进行调试。 2017-02-24 21:01:59.807 EOB-Reader[78109:10751346] * 中的断言失败 -[UIView _layoutEngine_didAddLayoutConstraint:roundingAdjustment:mutuallyExclusiveConstraints:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3600.6.21/NSLayoutConstraint_UIKitAdditions.m:649 2017-02-24 21:01:59.951 EOB-Reader[78109:10751346] * 终止应用 由于未捕获的异常“NSInternalInconsistencyException”,原因: '不可能在未准备好视图层次结构的情况下设置布局 约束。'
我还更新了原始帖子中的代码。
【问题讨论】:
标签: swift swift3 nslayoutconstraint