Swift,Constraint,视图层次结构不是为约束准备的

时间:2014-12-14 02:10:28

标签: swift uinavigationcontroller uiimageview constraints

我试图在导航控制器中添加图像并将其居中。所以我有一个imageView和一个UINavigationBar,我想将图片视图添加到该导航栏并将其水平居中。 UINavigationBar来自UINavigationController。我一直收到以下错误:

未为约束准备视图层次结构:     添加到视图时,约束的项必须是该视图的后代(或视图本身)。如果在组装视图层次结构之前需要解析约束,则会崩溃。打破 - [UIView _viewHierarchyUnpreparedForConstraint:]进行调试。

我尝试了不同的方法,但唯一有效的方法是我在imageView内设置self.view并将约束添加到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 个答案:

答案 0 :(得分:1)

正如我在评论中所说,如果你创建一个UIImageView并将titleView navigationItem设置为该图像视图,这似乎要容易得多。为了正确显示尺寸,您必须将contentMode设置为ScaleAspectFit,并将高度设置为" 30"或者你喜欢什么高度。下面你可以看到我是怎么做到的。

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

聚苯乙烯。我想你不必因ScaleAspectFit而设置宽度。