iOS 8 NavigationBar BackgroundImage

在iOS 8中,只有iPhone和iPad尺寸以及纵向和横向的概念发生了变化,因此设置导航栏背景图像的function不尽相同。 目前我使用下面的代码:

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上水平重复横条即可。 我已经看过图像切片,但我不认为这是解决scheme。

肖像景观

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

Objective-C的:

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

斯威夫特3/4:

 UINavigationBar.appearance().setBackgroundImage(UIImage(named: "image")!.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .stretch), for: .default) 
 [[UINavigationBar appearance] setBackgroundImage:[[UIImage imageNamed:@"navbarimg.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)] forBarMetrics:UIBarMetricsDefault]; 

使用上面的代码它的工作原理。并使用小尺寸的图像(40*navigarbarheight) 40是图像的宽度

这是更精确的示例代码,并适合所有的屏幕尺寸。 我会帮你的

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