Reputation:
I'm trying to center an image to a view but I'm getting error..this is my code:
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)
and my error is
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)
Upvotes: 2
Views: 54
Reputation: 154641
The constraints need to be added to the earliest common ancestor of the two views affected by the constraint. In this case, self.view
is earlier in the hierarchy so the constraints should be added to it instead of to imageview
.
Since iOS 8, there is an easier way. Once you've added your view to the view hierarchy (with addSubview
), you can activate the constraints instead of adding them to views.
You can do this by setting the isActive
property to true:
xConstraint.isActive = true
yConstraint.isActive = true
or by using the activate
class function of NSLayoutConstraint
to active multiple constraints:
NSLayoutConstraint.activate([xConstraint, yConstraint])
As mentioned by @dfd in the comments, you should also set this flag:
imageview.translatesAutoresizingMaskIntoConstraints = false
This tells iOS to not create constraints for imageview
based upon its frame. If you don't do this, you'll end up with conflicting constraints.
You are going to need width and height constraints for your imageview
as well, because you've only specified its position so far.
Upvotes: 1