ios - 无法将顶部约束添加到 View

标签 ios swift uiview autolayout constraints

我正在尝试以这种方式向 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.topLayoutGuideself.view 的子元素,不是 self.image。正如错误所说,在约束中引用来自安装约束的 View 子树之外的内容是非法的。

换句话说,self.imageself.topLayoutGuide 在 View 层次结构中是 sibling ,您必须将约束添加到这些 sibling 的“父亲”( self.view).

关于ios - 无法将顶部约束添加到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35088265/

相关文章:

iphone - 如何居中 UIActivityIndi​​cator?

ios - 所有这些自动布局更新方法之间有什么区别?都是必须的吗?

ios - 只有 imageView 的自适应表格 View 单元格

ios - 使用未解析的标识符 'NavigationLink' ;你的意思是 'NavigationView' 吗? - swift 用户界面

ios - 使用从 NSURLConnection 检索到的数据填充 UITableView

ios - 如何从其中包含许多 UITextview 的 UIView 复制和检索数据

ios - 为以编程方式生成的 View 实现自动布局

ios - 在 IOS 模拟器中生成屏幕上的图像

ios - 在 View Debugger 中查看时如何找到连接到任何 UIView 的相应 socket ?

ios - Autolayout 调整多个标签的大小