Objective-C: Background image and title in Navigat

2019-02-27 16:24发布

问题:

In need a background image AND a title in my Navigation Bar. For the image I write a category:

@implementation UINavigationBar(MyNavigationBar)
- (void)setBackgroundImage {
    UIImageView *aTabBarBackground = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"navBarBackgrd.png"]];
    [self addSubview: aTabBarBackground];
    [self sendSubviewToBack: aTabBarBackground];
    [aTabBarBackground release];
}
@end

I call this category in my AppDelegate and have background images in the whole application:

[navigationController.navigationBar setBackgroundImage]; 

Every ViewController has a title:

[self setTitle:@"MyTitle"];

But after setting the background image, I have a problem with the title.

In the first view every works, I see the background image and the title :-) But in the next view, the title disappears. Only the background image is visible. Maybe the title is under the image?

Technically it's possible to show both. With this trick it works:

  1. Hide Navigation Bar BEFORE opening the next ViewController:

    [self.navigationController setNavigationBarHidden:YES];

  2. Show the Navigation Bar in the next ViewController:

    [self.navigationController setNavigationBarHidden:NO];

Now, image AND title are visible, but this solution isn't the best ;-)

回答1:

I got it!

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

See Background image for navigation view



回答2:

After IOS5 You should do this, for example in AppDelegate


 UIImage *img = [[UIImage imageNamed:@"image.png"]resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
[[UINavigationBar appearance] setBackgroundImage:img forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setBarStyle:UIBarStyleBlackTranslucent];
[[UINavigationBar appearance] setTintColor:[UIColor colorWithRed:0 green: 0 blue:0  alpha:1]];