隐藏灰线

- 灰线其实是高度为1的shadowImage,所以可以通过设置它来改变样式。
先创建一个空的UIImage,让shadowImage变透明:
self.navigationController?.navigationBar.shadowImage = UIImage()
- 设置shadowImage还不够,不会起任何作用,还需要设置setBackgroundImage才可生效
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)

这时,灰线确实消失了,可是nav bar也变透明了,这是因为通过setBackgroundImage把bar的背景图片设置成了空图片
- 正好可以使用一张图片来弥补这种缺陷
self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "1.jpeg"), forBarMetrics: .Default)

- 那么如果不想要图片,只想要纯色而且没有灰线的nav bar呢?
第一种:加载纯色的图片。简单,不说了
第二种:通过UIColor创建UIImage:
之前用OC封装了一个UIImage的category,通过颜色创建纯色的图片,很方便。利用这个类可以创建纯色的nav bar
UIImage+UIColor.h
#import <UIKit/UIKit.h>
@interface UIImage(UIColor)
// 通过颜色创建UIImage
+(UIImage*)imageWithColor:(UIColor*) color;
@end
UIImage+UIColor.m
#import "UIImage+UIColor.h"
@implementation UIImage(UIColor)
+(UIImage*)imageWithColor:(UIColor*) color
{
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}
@end
使用:
self.navigationController?.navigationBar.setBackgroundImage(UIImage(color: UIColor.whiteColor()), forBarMetrics: .Default)

-
如果觉得还不够纯,可以设置navgationBar为不透明
不透明
网友评论