*************建议自定义,一定要用原生再看下去**************
我这边实现的是用原生导航栏做成渐变的,自定义的相对简单。上代码
为了好复制(你懂的),最近简书展示代码也很工整了👍
_navAlpha全局属性为了跳转上级页面返回的时候保持在原来滑动的高度
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
UIImage *image = [self imageWithColor:[UIColor colorWithWhite:1 alpha:_navAlpha] andSize:CGSizeMake(1, 1)];
[self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
[self.navigationController.navigationBar setShadowImage:[UIImage new]];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
[self.navigationController.navigationBar setShadowImage:nil];
}
#pragma mark 根据尺寸,颜色生成对应的图片
- (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size {
CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
CGContextAddEllipseInRect(context, rect);
UIGraphicsEndImageContext();
return image;
}
#pragma mark 滑动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat offset = scrollView.contentOffset.y/50;
offset = offset < 0 ? 0 : offset;
offset = offset > 1 ? 1 : offset;
UIImage *image = [self imageWithColor:[UIColor colorWithWhite:1 alpha:offset] andSize:CGSizeMake(1, 1)];
[self.navigationController.navigationBar setBackgroundImage:image
forBarMetrics:UIBarMetricsDefault];
_navAlpha = offset;
}