iOS 8导航栏背景图片

17

iOS 8改变了仅考虑iPhone和iPad尺寸以及纵向和横向的概念,因此设置导航栏背景图片不再起作用。目前我正在使用以下代码:

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];

从iOS 8开始,条形指标部分已被弃用。当我的应用在iPhone 6或6 Plus上运行时,它只是水平重复条形图像。我研究了图片切片,但我认为那也不是解决方案。

竖屏 横屏


你的问题解决了吗,Chris? - Ramesh Muthe
3个回答

76
我找到了解决方法。我需要使用resizableImageWithCapInsets:resizingMode:方法,并将resizingMode设置为UIImageResizingModeStretch,否则图像仍会平铺在导航栏中。

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)

在所有其他解决方案中,图像都会重复。你救了我的一天。 - Nidhin

4
[[UINavigationBar appearance] setBackgroundImage:[[UIImage imageNamed:@"navbarimg.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)] forBarMetrics:UIBarMetricsDefault];

使用上述代码可以正常工作。使用小尺寸图片(40 * 导航栏高度),其中40是图像的宽度。

抱歉,我更新了代码,显示我已经使用了可调整大小的图像插入,并且似乎并没有起作用。 - Chris

0

这是更精确和准确的示例代码,适合所有屏幕尺寸。它会有所帮助。

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];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接