一.导航栏
通常对导航栏的要求是:背景颜色,左右按钮颜色,标题字体颜色及大小。
再多一点要求:设置图片导航栏,设置导航栏渐变
还有一点就是去除导航栏下的一条细线
设置背景颜色:
self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
设置左右按钮颜色:
self.navigationController.navigationBar.tintColor = [UIColor darkGrayColor];
设置标题字体颜色及大小:
[self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor orangeColor],NSFontAttributeName:[UIFont systemFontOfSize:20]}];
设置图片导航栏:
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
但图片一般来讲需要进行剪裁至适合导航栏大小附带上图片剪裁的方法:
//简单粗暴地图片裁剪方法 裁剪出的图片尺寸按照size的尺寸,但图片可能会被拉伸 - (UIImage *)getNvaImageWithImage:(UIImage *)image{ CGSize imageSize = CGSizeMake(self.view.frame.size.width, kNavBarHeaderHeight); UIGraphicsBeginImageContext(imageSize); [image drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)]; UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; }
这里的kNavBarHeaderHeight为宏定义,用来区分iPhone X和其它机型的导航栏 可以用作iPhone X项目适配
///导航栏高度 #define kNavBarHeaderHeight ([UIScreen mainScreen].bounds.size.height == 812 88 : 64) ///iphone底部高度 #define kiPhoneFooterHeight ([UIScreen mainScreen].bounds.size.height == 812 34 : 0)
导航栏渐变我利用的是
[self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
方法来实现的
然后图片是根据颜色值生成的
核心代码:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView { //计算透明度 CGFloat alpha = scrollView.contentOffset.y/90.0f >1.0f 1:scrollView.contentOffset.y/90.0f; //将颜色转换为图片 UIImage *image = [self imageWithColor:[UIColor colorWithRed:0.094 green:0.514 blue:0.192 alpha:alpha]]; [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault]; }
遵循UIScrollViewDelegate代理,在滑动的方法里进行透明的计算,同时动态地给导航栏设置背景图片。
颜色转图片的方法:
- (UIImage *)imageWithColor:(UIColor *)color{ //创建1像素区域并开始图片绘制 CGRect rect = CGRectMake(0, 0, 1, 1); UIGraphicsBeginImageContext(rect.size); //创建画板并填充颜色和区域 CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect); //从画板上获取图片并关闭图片绘图 UIImage * image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }
去除导航栏下划线:
[self.navigationController.navigationBar setShadowImage:[UIImage new]];