1

I have the following code-snippets :

1.)

[[UINavigationBar appearance] setBackgroundImage:myImage forBarMetrics:UIBarMetricsDefault];

Where would I put that ?

or 2.)

@implementation UINavigationBar (BackgroundImage)
//This overridden implementation will patch up the NavBar with a custom Image instead of the title
- (void)drawRect:(CGRect)rect {
     UIImage *image = [UIImage imageNamed: @"NavigationBar.png"];
     [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end

Where would I put that ?

I have tried adding a navigation bar to my viewcontroller but I don't exactly know where to put these pieces of code.

the_critic
  • 12,720
  • 19
  • 67
  • 115
  • you can also ask what would you need to customize, for say changing entire navigation color/bar/titleImage... etc. – Splendid Jan 07 '12 at 16:43
  • Question seems like a duplicate, you can refer following thread - http://stackoverflow.com/questions/704558/custom-uinavigationbar-background – rishi Jan 07 '12 at 16:55

1 Answers1

1

Snippet 1 is iOS 5.0 only. You'd put that somewhere before your navigation bar is created so possibly in applicationDidFinishLaunching:. Take a look here for more information:

Snippet 2 is what you used to have to do before iOS 5.0. That's a category on UINavigationBar. I've not actually seen overriding drawRect: in a category before but it does appear that it works. Just create a category within your project on UINavigationBar and add that code. So something like:

UINavigationBar+MyCategory.h:

@interface UINavigationBar (MyCategory)
- (void)drawRect:(CGRect)rect;
@end

UINavigationBar+MyCategory.m:

#import "UINavigationBar+MyCategory.h"

@implementation UINavigationBar (MyCategory)
- (void)drawRect:(CGRect)rect {
     UIImage *image = [UIImage imageNamed: @"NavigationBar.png"];
     [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end
mattjgalloway
  • 34,792
  • 12
  • 100
  • 110
  • No need to put `drawRect` into the `.h` file. It is not public and should not be called directly. – Mundi Jan 07 '12 at 16:46
  • I am pretty new to objective-c, and unfortunately I happen to have never used a category...so basically I have to create a new class of UINavigationBar called `UINavigationBar+MyCategory.h` ? – the_critic Jan 07 '12 at 16:53
  • I suggest you go and read about what an Objective-C category is (try Wikipedia or Cocoa Dev Central) and then it should become clear. What I've shown is the 2 *files* to create and then add them to your project. – mattjgalloway Jan 07 '12 at 17:03
  • Ok thank you. Is it OK if I just subclass UINavigationBar and tell my Navbar in storyboard to be of this class ... Without making categories ? What are the upsides/downsides of my approach ? – the_critic Jan 07 '12 at 17:14
  • You could do that as well, yes. – mattjgalloway Jan 07 '12 at 18:06