- (void)viewWillAppear:(BOOL)animated {
//设置导航栏背景图片为一个空的image,这样就透明了
[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsCompact];
//去掉透明后导航栏下边的黑边
// [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
self.navigationController.navigationBar.translucent = YES;//这个必须设置
}
- (void)viewWillDisappear:(BOOL)animated {
// 返回时不让其他页面的导航栏变为透明 需要重置
[self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsCompact];
// [self.navigationController.navigationBar setShadowImage:nil];
self.navigationController.navigationBar.translucent = NO;
}
//如果要监听滚动而使导航栏颜色渐变,在scrollView的代理方法中添加代码
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//滑动渐变颜色
[self.navigationController.navigationBar setBackgroundImage:[self imageWithBgColor:[UIColor colorWithRed:18/255.0 green:151/255.0 blue:171/255.0 alpha:self.myTableView.contentOffset.y /100]] forBarMetrics:UIBarMetricsDefault];// 颜色自己设置 渐变开始的位置自己算
}
-(UIImage *)imageWithBgColor:(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 *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
/*------------导航栏常用属性--------*/
- 导航栏背景色设置:
self.navigationController.navigationBar.barTintColor = [UIColor greenColor];
- 导航栏标题颜色字体大小
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
attrs[NSFontAttributeName] = [UIFont systemFontOfSize:17];
[self.navigationController.navigationBar setTitleTextAttributes:attrs];
- 导航栏左右item
UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"left" style:UIBarButtonItemStylePlain target:self action:@selector(left)];
self.navigationItem.leftBarButtonItem = leftItem;
UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"right" style:UIBarButtonItemStylePlain target:self action:@selector(right)];
self.navigationItem.rightBarButtonItem = rightItem;
- 导航栏item字体颜色
self.navigationController.navigationBar.tintColor = [UIColor redColor];如果要不同item不同颜色,那么item要带一个自定义按钮,在设置按钮属性
- 当前控制器的下一个控制器的返回item去掉文字只保留箭头
UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
self.navigationItem.backBarButtonItem = backItem;