Custom Image on UINavigationBar for iOS <5.0

I use a "protective" code to set a custom image in the UINavigationBar - it works well on devices with ios5 or later.

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

Is this the right and 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];
    }
+3
source share
2 answers
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];
        }

Perhaps this will help you. he works for me.

+2
source

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 if the ifelse block is for the same.

NavIMage

+2

All Articles