如何让Tab Bar颜色不受ViewController背景色影响保持完全一致?
解决TabBar随ViewController背景色轻微变色的问题
我之前也碰到过一模一样的情况!其实这是iOS的TabBar默认的毛玻璃半透明效果在搞鬼——TabBar的translucent属性默认是开启的,它会混合下方视图的颜色,所以当ViewController的背景色变化时,视觉上TabBar的色调就会跟着轻微改变,哪怕你已经把视图的bottom锚定到了安全区域底部。
给你两个实用的解决方向,按需选择:
1. 直接关闭半透明效果(最简单)
如果你的设计不需要TabBar的毛玻璃质感,直接关闭半透明,TabBar就会用你设置的纯色显示,完全不受下方视图颜色影响:
// 在TabBarController或者AppDelegate/SceneDelegate里设置 tabBar.isTranslucent = false tabBar.barTintColor = .yourTargetColor // 设置你想要的固定颜色
2. 保留毛玻璃但固定色调(适合需要半透明效果的场景)
如果还想保留毛玻璃的视觉效果,又不想让它跟着背景变色,可以用UITabBarAppearance(iOS 13+)来固定背景样式,或者给TabBar添加一个自定义背景视图:
方法A:用UITabBarAppearance配置(推荐)
let tabBarAppearance = UITabBarAppearance() // 如果你想保留半透明,用configureWithTransparentBackground,然后设置backgroundColor tabBarAppearance.configureWithOpaqueBackground() // 或者configureWithTransparentBackground() tabBarAppearance.backgroundColor = .yourDesiredColor // 设置固定的背景色 // 应用到TabBar tabBar.standardAppearance = tabBarAppearance // iOS 15+需要额外设置scrollEdgeAppearance,适配页面滚动到顶部的情况 if #available(iOS 15.0, *) { tabBar.scrollEdgeAppearance = tabBarAppearance }
方法B:添加自定义背景视图
// 创建一个覆盖TabBar的背景视图 let customBackground = UIView(frame: tabBar.bounds) customBackground.backgroundColor = .yourDesiredColor // 设置自动适配TabBar的尺寸变化 customBackground.autoresizingMask = [.flexibleWidth, .flexibleHeight] // 把背景视图插入到TabBar的最底层,不影响按钮交互 tabBar.insertSubview(customBackground, at: 0)
补充一句:你之前调整视图的bottom锚点,只是让ViewController的视图不延伸到TabBar下方,但TabBar的毛玻璃还是会采样屏幕上的内容(包括ViewController的背景),所以还是会出现颜色变化。上面的方法从TabBar本身的样式入手,就能彻底解决这个问题啦!
内容的提问来源于stack exchange,提问作者user3628240




