我正在尝试以这种方式向 ImageView 和 super View 添加约束:
let newConstraint = NSLayoutConstraint(
item: self.image,
attribute: NSLayoutAttribute.Top,
relatedBy: NSLayoutRelation.Equal,
toItem: self.topLayoutGuide,
attribute: NSLayoutAttribute.Bottom,
multiplier: 1,
constant: 200)
image.addConstraint(newConstraint)
当我运行我的应用程序时,它崩溃并显示以下输出:
Unable to install constraint on view. Does the constraint reference something from outside the subtree of the view? That's illegal.
有什么想法吗?
最佳答案
将约束添加到 self.view
而不是 self.image
:
self.view.addConstraint(newConstraint)
self.topLayoutGuide
是 self.view
的子元素,不是 self.image
。正如错误所说,在约束中引用来自安装约束的 View 子树之外的内容是非法的。
换句话说,self.image
和self.topLayoutGuide
在 View 层次结构中是 sibling ,您必须将约束添加到这些 sibling 的“父亲”( self.view
).
关于ios - 无法将顶部约束添加到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35088265/