视图层次结构不是为约束准备的:

时间:2014-12-01 08:30:29

标签: swift uiscrollview nslayoutconstraint

我正在尝试为多个屏幕实现UIScrollView而没有明确的内容宽度我的Scroll View结构很简单

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

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

            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.

请帮忙解决问题

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

将视图添加到superview后,您已添加约束。