【发布时间】:2014-11-15 20:40:06
【问题描述】:
我正在尝试以编程方式进行简单的布局,但我想我缺少一些简单的东西,或者有一些不合适的东西。下面的 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。 Thisquestion 涉及到了一些话题,但是有点老了。
谁能指出我正确的方向?
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()
}
}
【问题讨论】:
标签: ios xcode swift visual-format-language