Tuesday, October 30, 2012

Custom UINavigationController UIToolbar Background Image


I have an iPhone application using UINavigationController and would like to customize the elements with custom background images. I was able to do this for the UINavigationController'sUINavigationBar pretty easily using Objective-C categories as below:
I'd like to do the same for the UINavigationController's UIToolbar, but the same approach doesn't seem to work (although I have absolutely no idea why not.) I've looked around and people seem to suggest subclassing UIToolbar, but this isn't possible for the UINavigationController'stoolbar, which is a read-only UIToolbar. I want to use the UINavigationController's toolbar instead of just making a subview toolbar because I'm using the slide-in setToolbarHidden animation.
Anyone have any idea if it's possible to apply a background image to this UINavigationControllertoolbar (most likely by somehow overriding the drawRect method)?





One of the best solutions is creating a category of UINavigationBar and UIToolbar. The next classes gives you a solution for iOS 4.0 and iOS 5.0 compatibility:
The only thing is you need to call the next methods in your viewDidLoad for example:
// Customizacion de navigation bar y toolbar compatible con iOS4 e iOS5
[UINavigationBar iOS5UINavigationBarBackgroundImage];
[UIToolbar iOS5UIToolbarBackgroundImage];    
So, the class Category for iOS 4.0 and iOS 5.0 compatibility for customize BackgroundImage results like follow:
@implementation UINavigationBar (BackgroundImage)
- (void)drawRect:(CGRect)rect 
{    
    UIImage* img = [UIImage imageNamed: @"navigation-bg.png"];
    [img drawInRect: CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];  
    [self setTintColor:UIColorFromRGB(0x5ca666)];      
}
+ (void) iOS5UINavigationBarBackgroundImage
{
    if ([UINavigationBar respondsToSelector: @selector(appearance)])
    {
        [[UINavigationBar appearance] setBackgroundImage: [UIImage imageNamed: @"navigation-bg.png"] forBarMetrics: UIBarMetricsDefault];
        [[UINavigationBar appearance] setTintColor:UIColorFromRGB(0x5ca666)];
    }
}
@end

@implementation UIToolbar (BackgroundImage)
- (void)drawRect:(CGRect)rect 
{
    UIImage *image = [UIImage imageNamed: @"toolbar-bg.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    [self setTintColor:UIColorFromRGB(0x5ca666)];
}
+ (void) iOS5UIToolbarBackgroundImage
{
    if ([UIToolbar respondsToSelector: @selector(appearance)])
    {
        [[UIToolbar appearance] setBackgroundImage:[UIImage imageNamed: @"toolbar-bg.png"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
        [[UIToolbar appearance] setTintColor:UIColorFromRGB(0x5ca666)];
    }
}
@end

No comments: