iOS 关于导航栏颜色渐变,导航条底部线条隐藏
2017-02-08 本文已影响251人
当阳桥
@interface SecViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,weak) UIView * line;//此处是weak
@end
self.navigationController.navigationBar.subviews的第一个视图是类是_UIBarBackground,控制该视图的alpha可以改变导航栏的透明度
self.navigationController.navigationBar.subviews.firstObject.subviews 的第一个视图是 UIImageView 这个视图就是底部的那条线
- (void)viewDidLoad {
[super viewDidLoad];
[self.navigationController.navigationBar.subviews.firstObject setAlpha:0];
[self.navigationController.navigationBar.subviews.firstObject.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj isMemberOfClass:[UIImageView class]]) {
obj.alpha = 0;//设置线条的透明度
_line = obj;
}
}];
}
每次进入控制器导航栏透明
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.navigationController.navigationBar.subviews.firstObject setAlpha:0];
}
离开时导航栏不透明
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self.navigationController.navigationBar.subviews.firstObject setAlpha:1];
}
// 经测试上面方法结束之后还会调用一下scrolview的代理导致setAlpha并不为1,采用离开时候调用下面的方法
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[self.navigationController.navigationBar.subviews.firstObject setAlpha:1];
}
监听scrollView的滚动改变导航栏透明度
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat currentOffset = scrollView.contentOffset.y;
CGFloat alphaHeight = (currentOffset+64)/200.0;
CGFloat alpha = alphaHeight<1?alphaHeight:1;
[self.navigationController.navigationBar.subviews.firstObject setAlpha:alpha];
if (alpha > 0.9) {
if (_line.alpha >= 1) return;
// 为了看的好看点,单独控制线条的透明度,避免看起来滚动时候线条还是看的比较明显
_line.alpha = alpha;
}else{
if (_line.alpha == 0) return;
_line.alpha = 0;
}
}