【问题标题】:Set background image of navigation bar for all bars为所有栏设置导航栏的背景图片
【发布时间】:2025-11-25 09:55:02
【问题描述】:

因为我更新到 xcode 4.2 和 iOS 5 以下代码无效:

@implementation UINavigationBar (CustomNavBarBG)
-(void)drawRect:(CGRect)rect{
    UIImage *image = [UIImage imageNamed:@"navbar.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    self.tintColor = [UIColor colorWithRed:124/255.0 green:177/255.0 blue:55/255.0 alpha:1.0];
}
@end

@implementation MyAppDelegate
//....

这应该将背景图像和颜色应用到导航栏。但是自从更新以来,我得到了默认的蓝色。我在我的项目中使用了three20框架。

知道为什么这不起作用吗?如何在一个位置而不是在每个视图控制器中设置所有导航栏的背景图像?

【问题讨论】:

标签: objective-c three20 uinavigationbar xcode4.2


【解决方案1】:

尝试设置:

[[UINavigationBar appearance] setBackgroundImage:myImage forBarMetrics:UIBarMetricsDefault];

在你的- (void) applicationDidFinishLaunching:(UIApplication *)application


编辑: 似乎也很有帮助:

[[UINavigationBar appearance] setTintColor:myColor]; 

【讨论】:

  • 好的,谢谢,你知道我可以如何设置色调颜色吗?当我将 setTintColor 改为 setBackgroundImage 时,找不到该方法...
  • 我做的物质效果! [[UINavigationBar 外观] setTintColor:myColor];
  • 实际上这就是我所做的“[[UINavigationBar 外观] setTintColor:[UIColor colorWithRed:124/255.0 green:177/255.0 blue:55/255.0 alpha:1.0]];”但是工具栏中的后退按钮仍然是蓝色的
  • 对于后退按钮,您需要再次设置不同的设置:我稍后会为您查找。
【解决方案2】:

ios5 中有本地方法可以更改背景图像。我为此创建了一个适用于 ios 4 和 5 的类别。(此处没有代码 atm)但应该不难创建。

[navBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];

【讨论】:

    【解决方案3】:

    我遇到了 [[UINavigationBar appearance] setBackgroundImage:myImage forBarMetrics:UIBarMetricsDefault]; 的相同问题,它在 iOS 4 上无法运行,但在 iOS 5 上运行良好。所以我尝试了另一种解决方案。

    image = [UIImage imageNamed:@"yourImageName.png"];
        if([[UINavigationBar class] respondsToSelector:@selector(appearance)]) //iOS >=5.0
        {
            [[UINavigationBar appearance] setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
        }
        else
        {
            UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
            [self.navigationController.navigationBar addSubview:imageView];
        }
    

    【讨论】:

      【解决方案4】:

      我有另一个解决方案,因为上面的解决方案 隐藏导航栏上的所有按钮

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

      【讨论】:

        【解决方案5】:

        如果您已经在 UINavigationBar 上设置了图像,并且希望在应用运行时更改它,请执行此操作。

        UIImage *NavigationPortraitBackground = [UIImage imageNamed:@"red_bg.png"];
        [[UINavigationBar appearance] setBackgroundImage:NavigationPortraitBackground forBarMetrics:UIBarMetricsDefault];
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"red_bg.png"] forBarMetrics:UIBarMetricsDefault];
        

        【讨论】: