美文网首页
如何给iPhone X导航栏设置成半透明

如何给iPhone X导航栏设置成半透明

作者: F麦子 | 来源:发表于2017-12-15 11:49 被阅读69次

最近写项目需要适配iPhone X,项目要求导航栏必须是自定义的透明度,通过查看iOS导航栏的相关API和图层,总结下方法:

首先因为iPhone X之前的导航栏高度都是64,而iPhone X安全区域以上的高度为88,所以需要写一个宏定义

#define SafeAreaTopHeight ([UIScreen mainScreen].bounds.size.height ==812.0?88:64)

,然后查看图层发现,能影响导航栏以上的背景颜色的有barTintcorlor和设置背景图片,但是设置barTintcolor貌似不能设置透明度,只能选择设置背景图片来实现

首先写一个工具方法,通过传递一个颜色和透明度来创建一个图片,方法如下:

//封装了一个方法,用来生成背景图片

+ (UIImage*)imageWithFrame:(CGRect)frame backgroundColor:(UIColor*)bgColor alphe:(CGFloat)alphe{

frame =CGRectMake(0,0, frame.size.width, frame.size.height);

UIColor*color =[bgColorcolorWithAlphaComponent:alphe];

UIGraphicsBeginImageContext(frame.size);

CGContextRefcontext =UIGraphicsGetCurrentContext();

CGContextSetFillColorWithColor(context, [colorCGColor]);

CGContextFillRect(context, frame);

UIImage*theImage =UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

returntheImage;

}

,然后设置导航栏背景图片

UINavigationBar * bar = self.navigationController.navigationBar;

UIImage*bgImage = [self imageWithFrame:CGRectMake(0,0,IPHONE_WIDTH,SafeAreaTopHeight) backgroundColor:[UIColorblackColor] alphe:0.5];

[bar setBackgroundImage:bgImage forBarMetrics:UIBarMetricsDefault];

小知识点:

[self.navigationController.navigationBar setTintColor: NE_BARCOLOR_WHITE];

[self.navigationController.navigationBar setBarTintColor: NE_BARCOLOR_ORANGE];

可以看出我的宏定义一个是白色,一个是橙色,设置tintColor后文字和图标变成白色,而背景变成橙色。

相关文章

网友评论

      本文标题:如何给iPhone X导航栏设置成半透明

      本文链接:https://www.haomeiwen.com/subject/ffgrwxtx.html