我正在尝试以编程方式进行简单的布局,并且我想要一些简单的东西,或者有一些不合适的东西,我想。以下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问题大部分都在使用nib,我想要避免这种情况,或者使用Obj-C
代替{{ 1}}。 This问题涉及这个主题,但有点旧。
有人能指出我正确的方向吗?
swift
答案 0 :(得分:4)
这些约束是在标签及其超级视图之间进行的。应该将约束添加到该超级视图,而不是标签。
答案 1 :(得分:3)
你快到了。只需替换以下行......
label1.addConstraints(label1_H) // Comment these 2 lines and it runs, but
label1.addConstraints(label1_V) // of course the label is upper left
...使用以下代码:
view.addConstraints(label1_H) // Comment these 2 lines and it runs, but
view.addConstraints(label1_V) // of course the label is upper left
但,约束H:|-[label1]-|"
和V:|-[label1]-|"
等同于H:|-8-[label1]-8-|"
和V:|-8-[label1]-8-|"
(有关详细信息,请参阅iOS Developer Library在默认边距上)。因此,这些约束并不意味着以您的标签为中心。事实上,你将拥有一个巨大的标签,它有8个单位的顶部,前导,尾部和底部边距到viewController的视图。
在layoutView()
方法中添加以下代码行,看看我的意思:
label1.backgroundColor = UIColor.orangeColor()
没关系,但如果你真的想要标注你的标签,你将不得不使用以下代码:
func layoutView() {
label1.text = "Click to see device configuration"
label1.backgroundColor = UIColor.orangeColor()
//Set number of lines of label1 to more than one if necessary (prevent long text from being truncated)
label1.numberOfLines = 0
label1.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(label1)
let xConstraint = NSLayoutConstraint(item: label1,
attribute: NSLayoutAttribute.CenterX,
relatedBy: NSLayoutRelation.Equal,
toItem: view,
attribute: NSLayoutAttribute.CenterX,
multiplier: 1.0,
constant: 0.0)
self.view.addConstraint(xConstraint)
let yConstraint = NSLayoutConstraint(item: label1,
attribute: NSLayoutAttribute.CenterY,
relatedBy: NSLayoutRelation.Equal,
toItem: view,
attribute: NSLayoutAttribute.CenterY,
multiplier: 1.0,
constant: 0)
self.view.addConstraint(yConstraint)
//Add leading and trailing margins if necessary (prevent long text content in label1 to be larger than screen)
let viewsDictionary = ["label1" : label1]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=10@750)-[label1]-(>=10@750)-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary))
}