设置自定义UINavigationBar的titleView [英] setting titleView of custom UINavigationBar
问题描述
我有一个自定义导航栏,它不会真正进行任何导航控制(应用程序只有一个视图),而是用作标题,以显示固体背景颜色的徽标。所以我在主视图控制器上放了一个导航栏并创建了一个插座,所以我可以在代码中引用它。 (顺便使用swift)。
I have a custom navigation bar that doesn't really do any navigation controlling (app only has one view) its instead used as a header to display the logo against a solid background colour. So I put a navigation bar onto the main view controller and created an outlet so I can reference it in the code. (Using swift by the way).
现在我正在努力将徽标图像设置在导航栏的中心。我需要使用titleView(而不是设置整个背景图像)。到目前为止,我读到的内容是在视图控制器中使用 self.navigationItem.titleView
,但我认为只有在使用UINavigationController时才有效。这是我到目前为止的代码:
Right now I'm struggling with setting the logo image in the center of the nav bar. I need to do this with the titleView (instead of setting an entire background image). So far what I've read says to use self.navigationItem.titleView
in the view controller, but I think that only works when using a UINavigationController. Here is my code so far:
@IBOutlet weak var navBar: UINavigationBar!
override func viewDidLoad() {
super.viewDidLoad()
let logoImage = UIImageView(frame: CGRect(x:0, y:0, width: 200, height: 45))
logoImage.contentMode = .ScaleAspectFit
let logo = UIImage(named: "logo.png")
logoImage.image = logo
self.navigationItem.titleView = logoImage
}
但这不起作用。如何使用这样的自定义UINavigationBar访问titleView?
But this doesn't work. How do I get access to the titleView using a custom UINavigationBar like this?
推荐答案
您需要访问 UINavigationBar
的 topItem
属性。
然后你可以用 UIImageView设置
topItem
的 titleView
code>。
You need to access UINavigationBar
's topItem
attribute.
Then you can set the topItem
's titleView
with a UIImageView
.
所以在你的情况下:
self.navBar.topItem?.titleView = logoImage
这篇关于设置自定义UINavigationBar的titleView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!