如何将图像放在UIViewController的navigati

如何将图像放在UIViewController的navigati

本文介绍了如何将图像放在UIViewController的navigationBar的中心?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段UIViewController的viewDidLoad中使用的代码.我没有错误.图片存在.我得到背景但没有图像.图片是一种徽标.

I have this snippet of code used in viewDidLoad of a UIViewController. I'va no errors. Images exists. I get the background but not the image. Image is a sort of logo.

if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {

    /* Background of navigationBar. */
    UIImage * navigationBarImage = [UIImage imageNamed:@"01_navbar_portrait.png"];
    [self.navigationController.navigationBar setBackgroundImage:navigationBarImage forBarMetrics:UIBarMetricsDefault];

    /* Image in navigationBar */
    UIImage * logoInNavigationBar = [UIImage imageNamed:@"01_logo.png"];
    UIImageView * logoView = [[UIImageView alloc] init];
    [logoView setImage:logoInNavigationBar];
    self.navigationController.navigationItem.titleView = logoView;

}

推荐答案

UINavigationController通过查看导航堆栈上最顶层视图控制器的navigationItem属性来管理导航栏.因此,要将视图更改为徽标,您需要在使用徽标的视图控制器(即根视图控制器或另一个压入堆栈的控制器)中进行设置.

The UINavigationController manages the navigation bar by looking at the navigationItem property of the top-most view controller on the navigation stack. So to change the view to a logo, you need to set this up in the view controller that uses the logo (i.e. the root view controller or another one that gets pushed on the stack).

在视图控制器的viewDidLoad中执行以下操作:

Do something like this in viewDidLoad of your view controller:

UIImage* logoImage = [UIImage imageNamed:@"logo.png"];
self.navigationItem.titleView = [[UIImageView alloc] initWithImage:logoImage];

在您的情况下,您设置了错误的导航项:

In your case, you are setting the wrong navigation item:

// Oops...
self.navigationController.navigationItem.titleView = logoView;
// Should be this:
self.navigationItem.titleView = logoView;

这篇关于如何将图像放在UIViewController的navigationBar的中心?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 02:59