iOS navigationBar和tabBar变透明 & navigationBar根据滑动距离的渐变色实现

    navigationBar变为纯透明

    //第一种方法

    //导航栏纯透明

    [self.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];

    //去掉导航栏底部的黑线

    self.navigationBar.shadowImage = [UIImage new];

    

    //第二种方法

    [[self.navigationBar subviews] objectAtIndex:0].alpha = 0;

 

 

    tabBar同理

    [self.tabBar setBackgroundImage:[UIImage new]];

    self.tabBar.shadowImage = [UIImage new];

 

    navigationBar根据滑动距离的渐变色实现

    //第一种

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView

    {

        CGFloat offsetToShow = 200.0;//滑动多少就完全显示

        CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow;

        [[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = alpha;

    }

    //第二种

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView

    {

        CGFloat offsetToShow = 200.0;

        CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow;

        

        [self.navigationController.navigationBar setShadowImage:[UIImage new]];

        [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor orangeColor]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;

    }

posted @ 2016-08-30 15:52  tongyuling  阅读(2495)  评论(0编辑  收藏  举报