Swift, Constraint, The view hierarchy is not prepared for the constraint

痴心易碎 提交于 2019-12-13 01:14:31

问题


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
))

回答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.



来源:https://stackoverflow.com/questions/27465671/swift-constraint-the-view-hierarchy-is-not-prepared-for-the-constraint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!