简体   繁体   English

UINavigationBar的背景图片

[英]Background Image for UINavigationBar

I am trying to set the background image for UINavigationBar. 我正在尝试为UINavigationBar设置背景图像。

I tried 2 types of methods, 我尝试了两种方法,

 1. [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"KnavigationBarImage.png"] forBarMetrics:UIBarMetricsDefault];

It is supported in ios 5, but crashes when run it in ios 4.3. 它在ios 5中受支持,但在ios 4.3中运行时会崩溃。

 2. self.navigationController.navigationBar.layer.contents = (id)[UIImage imageNamed:@"KnavigationBarImage.png"].CGImage;

It is working fine in ios 4 , But the image is not displaying in ios 5 Simulator. 它在ios 4中工作正常,但图像不在ios 5 Simulator中显示。

I need the code which should work in both version 4 and 5. 我需要的代码应该适用于版本4和版本5。

Please suggest me. 请建议我。

Thanks. 谢谢。

Write a method like this to find which OS the device has. 编写这样的方法来查找设备具有的操作系​​统。

static int sIsiOS5 = -1;
+(BOOL)isIOS5
{
    if( -1 == sIsiOS5)
    {
        sIsiOS5 = 0;
        if( [[UIScreen mainScreen] respondsToSelector:@selector(brightness)])
        {
            sIsiOS5 = 1;
        }
    }
    return sIsiOS5;
}

While setting the image, check as following and then set the image. 设置图像时,请检查如下,然后设置图像。

if ( [Utilities isIOS5] ) {
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"KnavigationBarImage.png"] forBarMetrics:UIBarMetricsDefault];
}
else
{
    self.navigationController.navigationBar.layer.contents = (id)[UIImage imageNamed:@"KnavigationBarImage.png"].CGImage;
}

In one of my apps I use this to set the navbar image for the whole app. 在我的一个应用程序中,我使用它来为整个应用程序设置导航栏图像。 Put in on top of your appdelegate file. 放入appdelegate文件的顶部。 Works in iOS 4.3 and 5.0. 适用于iOS 4.3和5.0。

//custom navbar
@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect
{
    UIImage *image = [UIImage imageNamed: @"NavBarLogo.png"];
    [image drawInRect:CGRectMake(0, -1, self.frame.size.width, self.frame.size.height + 5)];
}
@end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM