添加约束时出现运行时错误

时间:2016-12-22 13:09:37

标签: swift constraints views

我正在尝试将图片居中到视图但我收到错误..这是我的代码:

let markerimage = #imageLiteral(resourceName: "ic_new_mark_icon")

    let size = CGSize(width: 60, height: 60)

    var newimage = imageWithImage(image: markerimage, scaledToSize: size)

    var imageview = UIImageView(image: newimage)

    self.view.addSubview(imageview)


    let xConstraint = NSLayoutConstraint(item: imageview, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0)

    let yConstraint = NSLayoutConstraint(item: imageview, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1, constant: 0)

    imageview.addConstraint(xConstraint)
    imageview.addConstraint(yConstraint)

我的错误是

2016-12-22 16:29:11.305417 Googlemappractice[21426:362773] [LayoutConstraints] The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x600000285f00 UIImageView:0x7ff772f15560.centerX == UIView:0x7ff772c0bd30.centerX   (inactive)>
    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(UIConstraintBasedLayout) 

1 个答案:

答案 0 :(得分:1)

需要将约束添加到受约束影响的两个视图的最早共同祖先。在这种情况下,self.view在层次结构中较早,因此应将约束添加到它而不是imageview

从iOS 8开始,有一种更简单的方法。将视图添加到视图层次结构后(使用addSubview),您可以激活约束,而不是将它们添加到视图中。

您可以通过将isActive属性设置为true来执行此操作:

xConstraint.isActive = true
yConstraint.isActive = true

或使用activate的{​​{1}}类函数来激活多个约束:

NSLayoutConstraint

如评论中@dfd所述,您还应该设置此标志:

NSLayoutConstraint.activate([xConstraint, yConstraint])

这告诉iOS不要基于其框架为imageview.translatesAutoresizingMaskIntoConstraints = false 创建约束。如果你不这样做,你最终会遇到冲突的约束。

您的imageview也需要宽度和高度限制,因为到目前为止您只是指定了它的位置。