问题描述
我想在导航控制器中添加一个图像并将其居中。所以我有一个 imageView
和 UINavigationBar
,我想添加图像视图到导航栏,水平。 UINavigationBar
来自 UINavigationController
。我不断收到以下错误:
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:
视图层次结构没有为约束准备:
添加到视图时,约束的项必须该视图的后代(或视图本身)。如果约束需要在组合视图层次结构之前解决,这将崩溃。打开 - [UIView _viewHierarchyUnpreparedForConstraint:]来调试。
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.
我尝试了不同的方法,但是唯一一个正在工作的是如果我设置<$ c在 self.view
中添加<$ c> imageView 并将约束添加到 self.view
。
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
))
推荐答案
正如我在评论中所说的,创建一个UIImageView并设置 navigationItem
到该图像视图的 titleView
。为了正确显示大小,您必须将 contentMode
设置为 ScaleAspectFit
,并将高度设置为类似30或任何你喜欢的高度。下面你可以看到我是怎么做的。
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。我想你不必设置宽度,因为 ScaleAspectFit
。
Ps. I guess you don't have to set the width because of ScaleAspectFit
.
这篇关于Swift,Constraint,没有为约束准备视图层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!