如何更改UINavigationBar的背景?

Mos*_*she 5 iphone uinavigationbar tabbar ios

我想将我的UINavigationBar的背景更改为a [UIColor colorWithImage:],但它不起作用.我错过了什么?

编辑:

一旦我创建了我的子类,我在哪里设置UINavigationController来使用它?

Sim*_*ker 8

您可以使用tintColor属性来改变颜色UINavigationBar,但图像设为您必须提供自己的背景UINavigationBar子类并覆盖drawRect:方法,例如:

- (void)drawRect:(CGRect)rect {
    // Drawing code 
    UIImage *img = [UIImage imageNamed: @"background-image.png"];
    [img drawInRect:CGRectMake(0, 
                               0, 
                               self.frame.size.width, 
                               self.frame.size.height)];
}
Run Code Online (Sandbox Code Playgroud)

如果使用Interface Builder构建UI然后使用自定义导航栏,只需在Interface Builder中选择UINavigationBar元素,打开Inspector,在Identity选项卡中指定类字段中的UINavigationBar子类,如下所示:

显示自定义UINavigationBar子类的示例屏幕截图


Den*_*ssy 7

要在导航栏中显示图像,您必须自己绘制图像,这实际上并不难.将其另存为UINavigationBar+CustomBackground.m(它将自定义类别添加到UINavigationBar):

@implementation UINavigationBar (CustomBackground)

- (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed:@"NavMain.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}

@end
Run Code Online (Sandbox Code Playgroud)