【iOS】导航栏从透明状态切换为背景图片

项目有一个需求:导航栏从透明状态切换到指定的背景图片。本来以为只是一个状态的修改,但是现实总是会让我知道自己还是too young too simple。

导航栏

很简单嘛,一顿操作之后👇🏻

  • 添加导航栏背景图片
// 设置导航栏不透明
[self.navigationController.navigationBar setTranslucent:NO];
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageByApplyingAlpha:1.f image:LJImageNamed(@"navigationbar")] forBarMetrics:UIBarMetricsDefault];
  • 导航栏设置为透明
// 设置导航栏透明
[self.navigationController.navigationBar setTranslucent:YES];
[self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
[self.navigationController.navigationBar setShadowImage:[UIImage new]];

事情往往不会像想象中那么顺利的,编译执行后,就有了如下的结果:

错误的结果

这里就发现,在设置self.navigationController.navigationBar.translucent = NO之后,坐标零点从(0, 0)移动到了(0, 64)。那这个translucent属性起什么作用呢?

/*
 New behavior on iOS 7.
 Default is YES.
  You may force an opaque background by setting the property to NO.
 If the navigation bar has a custom background image, the default is inferred 
 from the alpha values of the image—YES if it has any pixel with alpha < 1.0
 If you send setTranslucent:YES to a bar with an opaque custom background image
 it will apply a system opacity less than 1.0 to the image.
 If you send setTranslucent:NO to a bar with a translucent custom background image
 it will provide an opaque background for the image using the bar's barTintColor if defined, or black
 for UIBarStyleBlack or white for UIBarStyleDefault if barTintColor is nil.
 */

@property(nonatomic,assign,getter=isTranslucent) BOOL translucent NS_AVAILABLE_IOS(3_0)   UI_APPEARANCE_SELECTOR; // Default is NO on iOS 6 and earlier. Always YES if barStyle is set to UIBarStyleBlackTranslucent

translucent在iOS7 之后有了新的特性。默认为YES。将该属性设置为NO将强制导航栏为不透明的背景。当导航栏背景图是自定义背景图片,该属性的默认值会受到图片的透明度值影响:如果图片中有任何一个像素的透明度小于1,则该属性默认为YES。
如果导航栏拥有不透明的自定义背景图时,设置该属性为YES,则系统会将改图片的不透明度置为一个小于1.0的值;如果导航栏拥有透明的自定义背景图时,设置该属性为NO,系统也将会有默认的设定:当barTintColor已经被设置,则将使用该颜色作为图片的背景;反之,则根据barStyle属性设定颜色,UIBarStyleDefault为白色背景、UIBarStyleBlack为黑色背景。

查看文档之后依旧没有解决我遇到的问题,这个时候,那就只能靠GOOGLE了,最终找到了解决的答案:self.extendedLayoutIncludesOpaqueBars = YES;从属性名就可以得知该属性的功能:拓展布局是否包含不透明的导航栏。

至此,需求就算完成了,撒花~~

资料

详解 iOS navigationBar 的设置问题

如有不正,感谢指出。
感谢开源!!!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容