chewy
chewy

Reputation: 8267

custom image on UINavigationBar for iOS < 5.0

I am using a "defensive" code to set a custom image to UINavigationBar bar - it works well on devices with ios5 or later.

After some answers, I am editing the code with a combined answer (see below)

Is this is right & elegant way to do this?

if ([[UINavigationBar class] respondsToSelector:@selector(appearance)]) {
        UIImage *backgroundImage = [UIImage imageNamed:@"tableTitleView.png"];
        [self.navigationController.navigationBar setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsDefault];
    }
    else
    {

        NSString *barBgPath = [[NSBundle mainBundle] pathForResource:@"tableTitleView" ofType:@"png"];
        [self.navigationController.navigationBar.layer setContents:(id)[UIImage imageWithContentsOfFile: barBgPath].CGImage];
    }

Upvotes: 3

Views: 506

Answers (2)

Abhishek Singh
Abhishek Singh

Reputation: 6166

You can use this method :-

#define kSCNavBarImageTag 6183746
#define kSCNavBarColor [UIColor colorWithRed:0.54 green:0.18 blue:0.03 alpha:1.0]


+ (void)customizeNavigationController:(UINavigationController *)navController
{
    UINavigationBar *navBar = [navController navigationBar];
    [navBar setTintColor:kSCNavBarColor];

    if ([navBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])
    {
        [navBar setBackgroundImage:[UIImage imageNamed:@"navigation-bar-bg.png"] forBarMetrics:UIBarMetricsDefault];
    }
    else
    {
        UIImageView *imageView = (UIImageView *)[navBar viewWithTag:kSCNavBarImageTag];
        if (imageView == nil)
        {
            imageView = [[UIImageView alloc] initWithImage:
                        [UIImage imageNamed:@"navigation-bar-bg.png"]];
            [imageView setTag:kSCNavBarImageTag];
            [navBar insertSubview:imageView atIndex:0];
            [imageView release];
        }
    }
}

it will work on both ios 4 and 5 the if ..else block is for the same.

There is a good NavIMage tutorial

Upvotes: 2

ChintaN -Maddy- Ramani
ChintaN -Maddy- Ramani

Reputation: 5164

float version = [[[UIDevice currentDevice] systemVersion] floatValue];
        NSLog(@"%f",version);
        if (version >= 5.0) {
            UIImage *backgroundImage = [UIImage imageNamed:@"Myimage.png"];
            [self.navigationController.navigationBar setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsDefault];
        }
        else
        {

            NSString *barBgPath = [[NSBundle mainBundle] pathForResource:@"Myimage" ofType:@"png"];
            [self.navigationController.navigationBar.layer setContents:(id)[UIImage imageWithContentsOfFile: barBgPath].CGImage];
        }

Maybe it will help you. it works for me.

Upvotes: 2

Related Questions