Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an image to UINavigationBar

I need to support iOS4 and iOS5. My code works well on iOS4, but don't work on iOS5. How to fix the problem.

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"E_44.png"]];
imageView.frame = CGRectMake(136, 0, 52, 44);
[self.navigationController.navigationBar insertSubview:imageView atIndex:0];
[imageView release];
like image 251
Voloda2 Avatar asked Dec 21 '22 05:12

Voloda2


1 Answers

Setting custom background for UINavigationBar to support iOS5 and iOS4 too!


As you know, until iOS 5 came out, we used drawRect override in AppDelegate to customize UINavigationBar. But know, iOS 5 give us some new method for styling (and old doesn’t work).

How to build app that will work on iOS 4 and iOS 5 with stylized UINavigationBar?

You must to do both!

In AppDelegate use this code:

@implementation UINavigationBar (UINavigationBarCategory)
- (void)drawRect:(CGRect)rect {
UIImage *img = [UIImage imageNamed:@"navbar.png"];
[img drawInRect:rect];
}
@end

and in viewDidLoad method for iOS5 (in your view implementation):

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

If you see, here we are asking if navbar will respondToSelector to avoid crash on iOS4!

like image 120
StackFlowed Avatar answered Jan 11 '23 05:01

StackFlowed