You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UINavigationBar设置isTranslucent=false后自定义backgroundColor失效如何解决?

问题原因

当你将UINavigationBar的isTranslucent属性设为false时,系统会自动创建一层不透明的背景遮罩层,你直接设置的backgroundColor是作用在导航栏的底层视图上,会被这层遮罩层覆盖,所以无法显示你设置的棕色。仅在isTranslucent为true时,系统不会生成这层遮罩,直接设置的背景色才能正常显示。


正确解决方案

方案1:使用UINavigationBarAppearance配置(推荐,兼容iOS13+)

iOS13之后官方推荐通过Appearance对象统一配置导航栏样式,不受translucent属性影响,适配性更强:

let navBarAppearance = UINavigationBarAppearance()
// 设置不透明棕色背景
navBarAppearance.backgroundColor = UIColor(named: "brown")
// 可选:去掉导航栏底部的分割线
navBarAppearance.shadowColor = nil

// 应用到所有滚动状态的导航栏
UINavigationBar.appearance().standardAppearance = navBarAppearance
UINavigationBar.appearance().scrollEdgeAppearance = navBarAppearance
// 兼容小屏横屏的紧凑样式
if #available(iOS 15.0, *) {
    UINavigationBar.appearance().compactAppearance = navBarAppearance
}
// 无需手动设置isTranslucent,当Appearance配置了不透明背景色时,系统会自动将translucent设为false

方案2:旧版本兼容写法(iOS13以下)

如果项目需要支持iOS12及更早版本,可通过设置纯色背景图片的方式实现:

// 新增UIColor扩展,生成纯色1x1图片
extension UIColor {
    func toImage(size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
        let renderer = UIGraphicsImageRenderer(size: size)
        return renderer.image { context in
            self.setFill()
            context.fill(CGRect(origin: .zero, size: size))
        }
    }
}

// 全局配置导航栏
UINavigationBar.appearance().setBackgroundImage(UIColor(named: "brown")?.toImage(), for: .default)
UINavigationBar.appearance().isTranslucent = false
// 可选:去掉导航栏底部分割线
UINavigationBar.appearance().shadowImage = UIImage()

内容的提问来源于stack exchange,提问作者Kenny Wyland

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 12:27:03