I'm trying to add an image inside the navigation constroller and center it. So I do have an imageView
and a UINavigationBar
and I want to add the image view to that navigation bar and center it horizontally. The UINavigationBar
comes from the UINavigationController
. I keep getting the following error:
The view hierarchy is not prepared for the constraint: 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 _viewHierarchyUnpreparedForConstraint:] to debug.
I tried different approaches but the only one that was working was if I was setting the imageView
within self.view
and adding the constraint to self.view
.
let bar: UINavigationBar = self.navigationController!.navigationBar
let logo = UIImage(named: "logo-horizontal")
let imageView:UIImageView = UIImageView(image:logo)
imageView.setTranslatesAutoresizingMaskIntoConstraints(false)
imageView.frame.size.width = 100;
imageView.frame.size.height = 31;
bar.addSubview(imageView)
imageView.addConstraint(NSLayoutConstraint(
item: imageView,
attribute: NSLayoutAttribute.CenterX,
relatedBy: NSLayoutRelation.Equal,
toItem: bar,
attribute: NSLayoutAttribute.CenterX,
multiplier: 1,
constant: 0
))