Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

iphone - Changing the UINavigationBar background image

I've been trying to change the background image of the UINavigationBar of my application. I tried several ways. First I added to my AppDelegate class the following code:

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

But it wasn't working. My next try was to write a CustomizedNavigationBar Class which is overriding the drawRect method. It looked like that:

CustomizedNavigationBar.h

#import <UIKit/UIKit.h>

@interface CustomizedNavigationBar : UINavigationBar

@end

CustomizedNavigationBar.m

#import "CustomizedNavigationBar.h"

@implementation CustomizedNavigationBar

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

    NSLog(@"I got called!!!!!");
}

@end

In my .xib file where the NavigationBar is defined I changed the class to the new CustomizedNavigationBar. But still it is not working..

As another test I downloaded an example project where the background image should be changed. But even with that sample code it was not working.

What am I doing wrong? I am using IOS 5. Any suggestions or other ways I could define a background image?

Thanks for your answers!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Starting in iOS 5 you should use the -setBackgroundImage:forBarMetrics: method:

[myNavbar setBackgroundImage:[UIImage imageNamed: @"UINavigationBarBackground.png"] 
               forBarMetrics:UIBarMetricsDefault];

And in Swift 4:

navigationBar.setBackgroundImage(UIImage(named: "UINavigationBarBackground.png"),
               for: .default)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...