iPhone X应用中如何获取导航栏实际显示颜色以设置同色Footer?
我之前也踩过这个坑!iPhone X及以后的机型上,导航栏设置barTintColor后,系统会自动添加UIVisualEffect模糊层,导致实际显示的颜色是原barTintColor经过模糊叠加后的浅色调——直接给Footer设置相同的backgroundColor自然会比导航栏深,视觉上完全不一致。下面两个方法亲测有效:
方法一:直接复用导航栏的背景视图(最简单高效)
导航栏的背景其实已经包含了所有模糊和颜色叠加效果,我们可以直接把它的快照视图放到Footer上,100%匹配视觉效果:
// 保留你的Footer创建代码,调整背景为透明 self.footerView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 35, self.view.width, 35)]; self.footerView.backgroundColor = [UIColor clearColor]; // 关键:设为透明,避免覆盖模糊层 [self.view addSubview:self.footerView]; // 获取导航栏的背景视图并生成快照 UIView *navBarBackground = self.navigationController.navigationBar.subviews.firstObject; UIView *footerBackground = [navBarBackground snapshotViewAfterScreenUpdates:YES]; footerBackground.frame = self.footerView.bounds; [self.footerView addSubview:footerBackground];
这个方法的好处是完全不用纠结模糊参数和颜色透明度,直接复制导航栏的最终视觉效果,适合大多数场景。如果导航栏会动态变化(比如滚动时样式切换),只需要在变化时重新生成快照替换即可。
方法二:手动创建匹配的模糊+颜色叠加层(更灵活)
如果快照方法不满足你的动态需求,可以手动构建和导航栏一致的模糊效果:
// 创建Footer并设为透明 self.footerView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 35, self.view.width, 35)]; self.footerView.backgroundColor = [UIColor clearColor]; [self.view addSubview:self.footerView]; // 1. 创建匹配导航栏的模糊效果 UIBlurEffectStyle blurStyle; if (self.navigationController.navigationBar.barStyle == UIBarStyleDefault) { blurStyle = UIBlurEffectStyleExtraLight; // 默认导航栏对应浅色模糊 } else { blurStyle = UIBlurEffectStyleDark; // 黑色导航栏对应深色模糊 } UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:blurStyle]; UIVisualEffectView *blurView = [[UIVisualEffectView alloc] initWithEffect:blurEffect]; blurView.frame = self.footerView.bounds; // 2. 添加和导航栏barTintColor一致的颜色覆盖层(调整透明度匹配导航栏效果) UIView *tintOverlay = [[UIView alloc] initWithFrame:blurView.bounds]; tintOverlay.backgroundColor = self.navigationController.navigationBar.barTintColor; tintOverlay.alpha = 0.8; // 这个值可以根据实际显示微调,导航栏默认叠加透明度约0.8 // 3. 把模糊层和覆盖层添加到Footer [self.footerView addSubview:blurView]; [blurView.contentView addSubview:tintOverlay];
额外注意事项
- 确保导航栏的
translucent属性为YES(默认是YES),如果设为NO,导航栏不会有模糊效果,直接设置Footer的backgroundColor为barTintColor即可。 - 如果你的导航栏用了自定义的模糊样式,可以通过打印导航栏的子视图结构,找到对应的
UIVisualEffectView,复用它的effect属性。
内容的提问来源于stack exchange,提问作者Laurine Baillet
相关产品推荐
相关产品推荐

