Tutorial :Adding background Image in UINavigationBar


Is there a way to add an image in the background of UINavigationBar. There is no direct option through interface builder but I have seen apps implemented this thing.

Any help would be appreciated.



Create a UIView and add it as a subview.

Edit: You can now use setBackgroundImage:forBarMetrics:. Source: https://stackoverflow.com/a/7765102/313875


Use this code

        UIImage *backgroundImage = [UIImage imageNamed:@"strip.png"];          [upnavbar setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsDefault];  

this wil work.


Just add your background as a subview, as jrtc27 suggested and change the tint color according your needs.


You can also override the drawLayer:inContext: method in a UINavigationBar category class. Inside the drawLayer:inContext: method, you can draw the background image you want to use. You can also use different sized images for portrait and landscape orientations if you'd like to.

- (void) drawLayer:(CALayer *)layer inContext:(CGContextRef)context  {      if ([self isMemberOfClass:[UINavigationBar class]] == NO) {          return;      }        UIImage *image = (self.frame.size.width > 320) ?                          [UINavigationBar bgImageLandscape] : [UINavigationBar bgImagePortrait];      CGContextClip(context);      CGContextTranslateCTM(context, 0, image.size.height);      CGContextScaleCTM(context, 1.0, -1.0);      CGContextDrawImage(context, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), image.CGImage);  }  

And as a complete demo Xcode project on customizing the appearance of UINavigationBar this and this might be helpful.


I recently wrote an article about customization of background for UINavigatioBar and UIToolbar. You can find a code sample and categories for seamless integration of this functionality in your app by following link â€" http://leonov.co/2011/04/uinavigationbar-and-uitoolbar-customization-ultimate-solution/


You can also override the drawRect function.

@implementation UINavigationBar (UINavigationBarCustom)    - (void)drawRect:(CGRect)rect {        UIImage *image = [UIImage imageNamed:@"nav_bar_logo.png"];      [image drawInRect:rect];  }    @end  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »