R2D2
R2D2

Reputation: 2640

UINavigationBar background - how to cover all sizes, resolutions and devices?

I have the following code that works fine for setting a background image:

[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"navbar_bg.png"] forBarMetrics:UIBarMetricsDefault];

My question is, for Xcode6, iOS8/9, iPhone 5, 6, 6+, iPad, etc, how do I make sure I cover all devices, widths and resolutions, to make sure that my background image always fills the navigation bar correctly?

I have seen other questions on SO and various other sites, but all have been 2-4 years old, and so don't mention or cover the latest device widths and resolutions.

I want to use a background image in the navigation bar, but I need to make sure it looks good on all possible devices.

Upvotes: 0

Views: 349

Answers (1)

Mika
Mika

Reputation: 5845

All you have to do is have three versions of your image in your asset catalogue. The first in the size you need the second twice the size and the third three times the size. Xcode will put the right image on the right device.

Alternatively you can just put a vectorial image and at complie time Xcode will generate the three images for you on the fly.

For the navigation bar you need separate images for portrait and landscape. You can write something like this:

UIImage *portraitImage = [UIImage imageNamed:@"test_bar_portrait.png"];
UIImage *landscapeImage = [UIImage imageNamed:@"test_bar_landscape.png"];
[[UINavigationBar appearance] setBackgroundImage:portraitImage forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setBackgroundImage:landscapeImage forBarMetrics:UIBarMetricsLandscapePhone];
self.navigationController.navigationBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;

Upvotes: 1

Related Questions