美文网首页iOS DeveloperiOS学习笔记
导航栏透明下拉半透明

导航栏透明下拉半透明

作者: 安处幽篁兮 | 来源:发表于2016-12-26 13:37 被阅读0次

    需求:

    1. 导航栏透明
    2. 下拉变色

    实现:
    第一步:创建基类
    BaseScrollViewController 继承自UIViewController

    @interface BaseScrollViewController () <UIScrollViewDelegate,UINavigationControllerDelegate>
    
    @property (nonatomic, strong) UIScrollView *scrollView;
    
    @end
    

    loadView:This is where subclasses should create their custom view hierarchy if they aren't using a nib. Should never be called directly.这是当他们没有正在使用nib视图页面,子类将会创建自己的自定义视图层。绝不能直接调用。
    从nib/storyBoard载入视图 。除非你没有使用xib文件创建视图。

    - (void)loadView{
        // 根视图更为滚动视图
        self.scrollView = [[UIScrollView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        self.view = self.scrollView;
        self.scrollView.delegate = self;
    }
    

    viewWillAppear: Called when the view is about to made visible. Default does nothing视图即将可见时调用。默认情况下不执行任何操作。由于产品要求下一页的NavBar的和上页的并不同,所以在此方法里写,这样切换界面都可以调用到。

    - (void)viewWillAppear:(BOOL)animated {
        [super viewWillAppear:animated];
        self.automaticallyAdjustsScrollViewInsets = NO;
        [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
        // 设置透明
        [[[self.navigationController.navigationBar subviews]objectAtIndex:0] setAlpha:0];
        self.view.backgroundColor = [AXUtils colorWithString:@"ffffff"];
        self.navigationController.delegate = self;
        [self scrollViewDidScroll:self.scrollView];
        //    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    }
    

    viewWillDisappear :Called when the view is dismissed, covered or otherwise hidden. Default does nothing视图被驳回时调用,覆盖或以其他方式隐藏。默认情况下不执行任何操作。
    若是自定义的NavBar,在此reset销毁

    - (void)viewWillDisappear:(BOOL)animated {
        [super viewWillDisappear:animated];
    //    [self.navigationController.navigationBar reset];
    }
    

    下拉变色的实现方法

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView
    {
        CGFloat offsetY = scrollView.contentOffset.y;
        // 滑动超过设定值即半透明
        if (offsetY > ScaleHeight(50)) {
            CGFloat alpha = MIN(0.8, 1 - ((ScaleHeight(50) + 64 - offsetY) / 64));
            [self.navigationController.navigationBar setBackgroundImage:[AXUtils imageWithString:@"000000"] forBarMetrics:UIBarMetricsDefault];
            [[[self.navigationController.navigationBar subviews]objectAtIndex:0] setAlpha:alpha];
        } else {
            [[[self.navigationController.navigationBar subviews]objectAtIndex:0] setAlpha:0];
        }
    }
    

    总结:UI切图就好了,嘿嘿嘿~

    相关文章

      网友评论

        本文标题:导航栏透明下拉半透明

        本文链接:https://www.haomeiwen.com/subject/igpomttx.html