iOS导航栏动态透明

3,433 阅读1分钟

iOS空白页占位图

优质博客

- (void)viewWillAppear:(BOOL)animated
{
  [super viewWillAppear:animated];
  
  //导航栏纯透明
  
  [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
  //去掉导航栏底部的黑线
  
  self.navigationController.navigationBar.shadowImage = [UIImage new];
  
}
//保证进入下个界面nav正常显示
- (void)viewWillDisappear:(BOOL)animated {
  
  [super viewWillDisappear:animated];
  // 不透明
  [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:0];
  
  [self.navigationController.navigationBar setShadowImage:nil];
}

滑动显示

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
  CGFloat offsetToShow = 30.0;
  
  CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow;
  
  [self.navigationController.navigationBar setShadowImage:[UIImage new]];
  
  [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[NavBarColor colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault];
  
}

//生成一张纯色的图片
- (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;
  
}