iOS 导航栏渐变

效果图.gif

直接上代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    ///iOS 15更新后,导航栏变白,静止情况看不清
    if (@available(iOS 13.0, *)) {
        UINavigationBarAppearance *appearance = [UINavigationBarAppearance new];
        [appearance configureWithOpaqueBackground];
        appearance.backgroundColor = [UIColor purpleColor];
        self.navigationController.navigationBar.standardAppearance = appearance;
        self.navigationController.navigationBar.scrollEdgeAppearance = self.navigationController.navigationBar.standardAppearance;
    } else {
        // Fallback on earlier versions
    }
    
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBar.subviews[0].alpha = 0;
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 设置导航栏为透明,并根据当前tableView的偏移量设置对应的 alpha
    self.navigationController.navigationBar.translucent = YES;
    [self setNavigationBarColorWithOffsetY:self.table.contentOffset.y];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 设置导航栏 为不透明
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.subviews[0].alpha = 1.0;
}
//监听scrollView滑动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.table) {
        CGFloat offsetY = scrollView.contentOffset.y;
        [self setNavigationBarColorWithOffsetY:offsetY];
    }
}

// 界面滑动时导航栏随偏移量 实时变化
- (void)setNavigationBarColorWithOffsetY:(CGFloat)offsetY {
    UIImageView *backView = self.navigationController.navigationBar.subviews[0];
    if (offsetY <= 0) {
        backView.alpha = 0;
        self.lab.textColor = [UIColor redColor]; //这里可以根据UI设置导航栏上的控件显示的颜色
    } else if (offsetY > 0 && offsetY < 91) {
        backView.alpha = offsetY / 91;
    } else if (offsetY >= 91 ) {//&& offsetY <= NavBar_HEIGHT + 30
        backView.alpha = 1;
        self.lab.textColor = [UIColor yellowColor]; //这里可以根据UI设置导航栏上的控件显示的颜色
    }
}

这是一种实现方法,另一种可以使用kvo监听 contentOffset.y 也可以实现。
需要写上

superScrollView .addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)

然后,再监听回调中,实现导航渐变

你可能感兴趣的:(iOS 导航栏渐变)