我正在尝试以编程方式进行简单的布局,并且我错过了一些简单的事情,或者有一些不合适的地方,我想。以下ViewController应该将标签置于超级视图中。然而,它与这个修剪消息崩溃:The view hierarchy is not prepared for the constraint ... When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled... View not found in container hierarchy: ... That view's superview: NO SUPERVIEW
其他SO问题与此错误消息大部分使用笔尖,我想要避免,或使用Obj-C
而不是swift
。 This问题处理这个话题有点但有点老了。swift中的VFL约束:由于没有超级视图导致的崩溃
任何人都可以指向正确的方向吗?
class ViewController: UIViewController {
let label1 = UILabel() as UILabel
func layoutView(){
label1.text = "Click to see device configuration"
label1.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(label1)
let viewsDictionary = ["label1":label1]
let label1_H:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label1]-|",
options: NSLayoutFormatOptions(0),
metrics: nil,
views: viewsDictionary)
let label1_V:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[label1]-|",
options: NSLayoutFormatOptions(0),
metrics: nil, views:
viewsDictionary)
label1.addConstraints(label1_H) // Comment these 2 lines and it runs, but
label1.addConstraints(label1_V) // of course the label is upper left
}
override func viewDidLoad() {
super.viewDidLoad()
layoutView()
}
}
谢谢 - 我正在调整一个例子,并不完全理解这个过程。 – 2014-09-22 00:12:38