无法将顶部约束添加到视图

Cannot add top constraint to a 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.topLayoutGuideself.view 的子元素,而不是 self.image。正如错误所说,在约束中引用来自安装约束的视图子树之外的内容是非法的。

也就是说,self.imageself.topLayoutGuide在视图层级中是兄弟姐妹,必须给这些兄弟姐妹的"father"添加约束(self.view) .

对于那些对 Interface Builder (StoryBoard) 解决方案感兴趣的人:

如果top/bottom约束无法add/edit如图所示。

首先,select 您希望在“导航到相关项目”窗格中添加这些约束的项目,然后按住 CTRL 键单击它到视图中附近的项目并约束其 top/bottom任意到那个项目。

这会创建一个您无法添加的约束,您现在可以找到它,并打开属性检查器进行编辑;因此,任意初始选择。

虽然这似乎只有在您的视图包含您能够毫无问题地约束的其他项目时才有效,因为添加此约束将取决于至少一个已经存在的项目。