Sunday, June 9, 2013

UINavigationBar setBackgroundImage forBarMetrics example in Objective C (iOS).


UINavigationBar setBackgroundImage forBarMetrics

Sets the background image for given bar metrics.

- (void)setBackgroundImage:(UIImage *)backgroundImage forBarMetrics:(UIBarMetrics)barMetrics

Parameters of [UINavigationBar setBackgroundImage forBarMetrics]
backgroundImage
The background image to use for barMetrics.
barMetrics
A bar metrics constant.
UINavigationBar setBackgroundImage forBarMetrics example.
To apply image to all your navigation bars, use the appearance proxy:

[[UINavigationBar appearance] setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
For an individual bar:

// Assuming "self" is a view controller pushed on to a UINavigationController stack
[self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];

Example of [UINavigationBar setBackgroundImage forBarMetrics].
if( [self.navigationController.navigationBar respondsToSelector: @selector(setBackgroundImage:forBarMetrics:)]) {
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbar.png"]
                                                  forBarMetrics:UIBarMetricsDefault];

}else {
    UIImageView* imgBG = [[UIImageView alloc]init];
    imgBG.image = [UIImage imageNamed:@"navbar.png"];
    imgBG.frame = CGRectMake(-10,0, 330, 44);
    [parentViewLeft addSubview:imgBG];

}
UIBarButtonItem *customBarButtomLeft = [[UIBarButtonItem alloc] initWithCustomView:parentViewLeft];
self.navigationItem.leftBarButtonItem = customBarButtomLeft;

UINavigationBar setBackgroundImage forBarMetrics example.
If you use iOS4, you can override - (void)drawRect

@implementation UINavigationBar (UINavigationBarCategory)

- (void)drawRect:(CGRect)rect
{
    UIImage *navBg = [UIImage imageNamed:@"navBar.png"];
    [navBg drawInRect:rect];
}
@end
iOS 5,

if ([[UIDevice currentDevice].systemVersion floatValue] >= 5.0) {
    if ([self.navigationController.navigationBar respondsToSelector:@selector( setBackgroundImage:forBarMetrics:)]){

        UIImage *navBarImg = [UIImage imageNamed:@"navBar.png"];

        [self.navigationController.navigationBar setBackgroundImage:navBarImg forBarMetrics:UIBarMetricsDefault];

    }
}

End of UINavigationBar setBackgroundImage forBarMetrics example article.