斯威夫特回归"The view hierarchy is not prepared for the constraint"



我正在尝试为多个屏幕实现UIScrollView,而没有明确的内容宽度 我的滚动视图结构非常简单

                        UIScrollView(Leading , Trialing, Top , Bottom)
                            ContentView (Leading , Trialing, Top , Bottom, Placeholder h/w)

根据此Tutiorial向ContentView添加从左到右的约束,相对于ViewDidLoad中的主视图

            var leftConstraint : NSLayoutConstraint = NSLayoutConstraint(item: self.contentView!, attribute: NSLayoutAttribute.Leading, relatedBy:NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Left, multiplier: 1.0, constant: 0)
             self.view.addConstraint(leftConstraint)

            var rightConstraint : NSLayoutConstraint  = NSLayoutConstraint(item:          self.contentView!, attribute: NSLayoutAttribute.Trailing, relatedBy:NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: 0)
           self.view.addConstraint(rightConstraint)

但不幸的是我得到了

       The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x7d215170 UIView:0x7be9ac90.leading == UIView:0x7be9af50.left>
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. Break on -[UIView _viewHierarchyUnpreparedForConstraint:] to debug.

我该如何解决?

该错误可能表明视图不可用。确保在加载视图后设置约束。

在将视图添加到超级视图后,您添加了约束。

最新更新