1

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
))
manosim
  • 3,630
  • 12
  • 45
  • 68
  • I've just found [this one](http://stackoverflow.com/questions/289441/can-i-set-image-as-a-title-to-uinavigationbar) which uses a different approach. Do you think that's the right way? `self.navigationItem.titleView = imageView;` – manosim Dec 14 '14 at 02:42
  • The reason for your error is that you are adding the constraint to the `imageView` which is a subview of the navigation bar, which is used in the constraint. You need to add the constraint to a view that contains both of the views being referenced in the constraint. – Abizern Dec 28 '14 at 19:04

1 Answers1

1

So as said in my comment, it seems to be a lot easier if you create a UIImageView and set the titleView of navigationItem to that image view. In order for the size to be displayed correctly you have to set the contentMode to ScaleAspectFit and set the height to something like "30" or whatever height you like. Below you can see how i did it.

let logoView:UIImageView = UIImageView(image: UIImage(named: "logo-filename"))
logoView.contentMode = UIViewContentMode.ScaleAspectFit
logoView.frame.size.height = 30
self.navigationItem.titleView = logoView

Ps. I guess you don't have to set the width because of ScaleAspectFit.

manosim
  • 3,630
  • 12
  • 45
  • 68