UINavigationBar与图像和默认渐变背景与iOS5



我试图在iOS5中使用新的[UINavigationBar appearance]功能来添加徽标图像到我的应用程序中的UINavigationBars。首先,我想保留默认的渐变,但在导航栏中居中一个透明的png。标志图像大约120像素宽(240 pixels@2x)。

我首先尝试设置背景图像。setBackgroundImage:forBarMetrics:的默认行为似乎是平铺图像,所有透明部分都显示默认的导航条背景颜色,黑色。我也可以通过外观修改器设置背景颜色,并得到一个平坦的背景颜色,但我真的想得到原始的渐变行为,而不维护一个单独的图像资源。这也使得在代码中调整更容易,因为我可以在那里调整色调,而不是重新生成一个新的图像,如果我决定改变它。

我想用的:

UIImage *logoImage = [UIImage imageNamed:@"logoImage"];
[[UINavigationBar appearance] setBackgroundImage:logoImage forBarMetrics:UIBarMetricsDefault];

有两种方法。如果你想在导航栏中始终显示图像,那么创建一个图像视图并将其设置为导航栏的子视图:

[self setLogoImageView:[[UIImageView alloc] init]];
[logoImageView setImage:[UIImage imageNamed:@"logo.png"]];
[logoImageView setContentMode:UIViewContentModeScaleAspectFit];
CGRect navFrame = [[navController navigationBar] frame];
float imageViewHeight = navFrame.size.height - 9;
float x_pos = navFrame.origin.x + navFrame.size.width/2 - 111/2;
float y_pos = navFrame.size.height/2 - imageViewHeight/2.0;
CGRect logoFrame = CGRectMake(x_pos, y_pos, 111, imageViewHeight);
[logoImageView setFrame:logoFrame];
[[[self navigationController] navigationBar] addSubview:logoImageView];

如果您只想在某个视图中显示徽标,则设置该视图的导航项:

[logoImageView setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
[[self navigationItem] setTitleView:logoImageView];