Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
    }
like image 681
chewy Avatar asked Dec 02 '25 14:12

chewy


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];
        }

Maybe it will help you. it works for me.

like image 158
ChintaN -Maddy- Ramani Avatar answered Dec 04 '25 05:12

ChintaN -Maddy- Ramani


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

like image 25
Abhishek Singh Avatar answered Dec 04 '25 04:12

Abhishek Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!