Adding an Image to the UINavigationBar

I need to support iOS4 and iOS5. My code works well on iOS4, but does not 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]; 
+4
source share
2 answers

Customizable background settings for UINavigationBar to support iOS5 and iOS4 too!


As you know, before iOS 5, we used drawRect overrides in AppDelegate to configure the UINavigationBar . But you know, iOS 5 gives us a new styling method (and the old one doesn't work).

How to create an application that will work on iOS 4 and iOS 5 with a stylized UINavigationBar ?

You must 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 for iOS5 (in your implementation):

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

If you see, here we ask if navbar will respond to the selection in order to avoid a crash on iOS4!

+8
source

This does not add background, but it will allow you to add an image to the navigation bar

  // Create your image<br> UIImage *image = [UIImage imageNamed: @"yourimage.png"];<br> UIImageView *imageview = [[UIImageView alloc] initWithImage: image]; // set the text view to the image view<br> self.navigationItem.titleView = imageView; 

Hope this helps.

+2
source

Source: https://habr.com/ru/post/1386097/


All Articles