iOS 8 NavigationBar BackgroundImage

2019-01-30 12:48发布

With iOS 8 the concept of just iPhone and iPad sizes along with portrait and landscape have changed and therefor setting the navigation bars background image isn't working the same. Currently i'm using the following code:

UIImage *NavigationPortraitBackground = [[UIImage imageNamed:@"nav-image-portrait"]
                                         resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];

UIImage *NavigationLandscapeBackground = [[UIImage imageNamed:@"nav-image-landscape"]
                                          resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];

[[UINavigationBar appearance] setBackgroundImage:NavigationPortraitBackground forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setBackgroundImage:NavigationLandscapeBackground forBarMetrics:UIBarMetricsCompact];

The bar metrics portion has been deprecated as of iOS 8. When starting up my app it simply repeats the bar image horizontally when on an iPhone 6 or 6 Plus. I've looked into image slices but i don't think thats the solution either.

portrait landscape

3条回答
地球回转人心会变
2楼-- · 2019-01-30 13:06

I found the solution. I needed to use the method resizableImageWithCapInsets:resizingMode: and set the resizingMode to UIImageResizingModeStretch, otherwise the image would still tile in the navigation bar.

Objective-C:

[[UIImage imageNamed:@"nav-image-portrait"]
                                         resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0) resizingMode:UIImageResizingModeStretch];

Swift 3 / 4:

UINavigationBar.appearance().setBackgroundImage(UIImage(named: "image")!.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .stretch), for: .default)
查看更多
Anthone
3楼-- · 2019-01-30 13:12
[[UINavigationBar appearance] setBackgroundImage:[[UIImage imageNamed:@"navbarimg.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)] forBarMetrics:UIBarMetricsDefault];

Use the above code it works.And use small size image (40*navigarbarheight) 40 is the width of the image

查看更多
在下西门庆
4楼-- · 2019-01-30 13:15

THis is sample code at more precis and accurate to fit on all the screen sizes . it will help

CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
[[UINavigationBar appearance] setBackgroundImage:[[UIImage imageNamed:@"header"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, screenWidth-50, 50)] forBarMetrics:UIBarMetricsDefault];
查看更多
登录 后发表回答