UINavigationBar - Setting background image?

扶醉桌前 提交于 2019-12-11 12:18:12

问题


So I have a category for UINavigationController and I override the init method as below

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
            UIImage *image = [UIImage imageNamed:@"navBar.png"];
            [[UINavigationBar appearance] setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];      
    }

        return self;
}

The following code causes the background image of the navigation bar to become blank (white). The image name is correct and it exists within the project. Any idea what is causing this problem?


回答1:


If you use iOS4, you can override - (void)drawRect

@implementation UINavigationBar (UINavigationBarCategory)

- (void)drawRect:(CGRect)rect
{
    UIImage *navBg = [UIImage imageNamed:@"navBar.png"];
    [navBg drawInRect:rect];
}
@end

iOS 5,

if ([[UIDevice currentDevice].systemVersion floatValue] >= 5.0) {
    if ([self.navigationController.navigationBar respondsToSelector:@selector( setBackgroundImage:forBarMetrics:)]){

        UIImage *navBarImg = [UIImage imageNamed:@"navBar.png"];

        [self.navigationController.navigationBar setBackgroundImage:navBarImg forBarMetrics:UIBarMetricsDefault];

    }
}


来源:https://stackoverflow.com/questions/9304817/uinavigationbar-setting-background-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!