Drawing a textured pattern over the default UINavigationBar
Say you want to draw a cool looking navigation bar, say with a slightly transparent pattern that is overlaying the default look of the nav bar, here’s how to do it.
Firstly, create a subclass of UINavigationBar:
#import "MyNavBar.h"
#import "QuartzCore/QuartzCore.h"
@implementation MyNavBar
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
UIImage *img = [UIImage imageNamed:@"MyTextureFile"];
CGContextSetAlpha(UIGraphicsGetCurrentContext(), 0.05);
[img drawAsPatternInRect:CGRectMake(0, 0,
self.frame.size.width, self.frame.size.height)];
CGContextSetAlpha(UIGraphicsGetCurrentContext(), 1);
}
@endThen, in your main XIB where your nav bar is declared, overwrite it’s class to be ‘MyNavBar’. That’s it!
The beauty of this technique over method swizzling or categories is that it allows your drawrect to call the original (super) drawrect, so that you can simply add a texture ‘on top’, instead of having to draw the gloss yourself.