Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the UINavigationBar background image

Tags:

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!

like image 742
Prine Avatar asked Oct 14 '11 07:10

Prine


People also ask

How do I change the navigation bar color in Swift?

navigationController. navigationBar. barTintColor = UIColor. newBlueColor() and of course this just changes the colour of the navigation bar of the view controller that the code is within.

How do I use the navigation bar in Xcode?

Start with Navigation ControllerCreate a single view application in Xcode. Add two view controller into your storyboard. Create two different swift files for those view controllers and set identifiers for them. Take a button in each view controller, set constrain for them and customize as you want.


1 Answers

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) 
like image 130
Craz Avatar answered Nov 13 '22 01:11

Craz