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

标签 swift constraints views

我正在尝试将图像置于 View 的中心,但出现错误。这是我的代码:

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) 

最佳答案

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

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

您可以通过将 isActive 属性设置为 true 来做到这一点:

xConstraint.isActive = true
yConstraint.isActive = true

或者使用NSLayoutConstraintactivate类函数来激活多个约束:

NSLayoutConstraint.activate([xConstraint, yConstraint])

正如@dfd 在评论中提到的,您还应该设置此标志:

imageview.translatesAutoresizingMaskIntoConstraints = false

这告诉 iOS 不要根据其框架为 imageview 创建约束。如果不这样做,您最终会遇到约束冲突。

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

关于swift - 添加约束时出现运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41283967/

相关文章:

views - CouchDB View : remove duplicates *and* order by time

macos - 不寻常的 Swift Idiom - 它实现了什么?

swift - 在 Mac OS 应用程序中使用控件

ios - 运行后 UIbutton 拉伸(stretch)

ios - 将图像限制在 Xcode Storyboard上的屏幕边缘

SQL View 或表

ios - Alamofire 无法使用 cocoapods 构建

ios - 使用 Swinject 将 ViewModel 有条件注入(inject)到 ViewController 中

Swift - 屏幕外的容器 View

sql-server - 如何在 SQL Server 中保存查询以使其在对象资源管理器中可见