DLende
DLende

Reputation: 5242

Changing the NavigationBar background to image

I tried this code on IOS 4+ and it works perfectly, but not until my teammates tested it on IOS 5+. This is the code

@implementation UINavigationBar (CustomImage)

// Set the navigation bar background
- (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed:@"background.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}

@end

I need a code that works on IOS 4+ and IOS 5+, please help me.

Upvotes: 2

Views: 114

Answers (1)

user1440738
user1440738

Reputation:

Please try this one:

@implementation UINavigationBar (CustomImage)

// Set bar background
- (UIImage *)customBackground {
    UIImage *image = [UIImage imageNamed:@"background.png"];
    return image;
}

- (void)didMoveToSuperview {
    // Applies to iOS5 only
    if ([self respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) {
        [self setBackgroundImage:[self customBackground] forBarMetrics:UIBarMetricsDefault];
    }
}

// Set the navigation bar background
- (void)drawRect:(CGRect)rect {
    [[self customBackground] drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}

@end

The setBackgroundImage:forBarMetrics: applies on iOS5

Upvotes: 3

Related Questions