我正在尝试将图像置于 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
或者使用NSLayoutConstraint
的activate
类函数来激活多个约束:
NSLayoutConstraint.activate([xConstraint, yConstraint])
正如@dfd 在评论中提到的,您还应该设置此标志:
imageview.translatesAutoresizingMaskIntoConstraints = false
这告诉 iOS 不要根据其框架为 imageview
创建约束。如果不这样做,您最终会遇到约束冲突。
您还需要为 imageview
设置宽度和高度限制,因为到目前为止您只指定了它的位置。
关于swift - 添加约束时出现运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41283967/