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

如何根据系统深浅色模式自动修改UINavigationBar标题文字属性?

解决SwiftUI中UINavigationBar标题颜色随深色/浅色模式自动切换的问题

你的问题核心在于:init方法只会在视图初始化时执行一次,而且在init里无法获取到SwiftUI的colorScheme环境变量,所以你写的模式判断逻辑不会随着系统模式切换而更新,自然无法生效。下面提供两种可行的解决方案:

方案一:使用UIKit动态UIColor(推荐)

直接借助UIKit的动态颜色特性,让颜色自动适配系统模式,无需依赖SwiftUI的colorScheme。这种方法适合全局设置导航栏样式:

init() {
    // 创建支持动态切换的颜色
    let dynamicTextColor = UIColor { traitCollection in
        traitCollection.userInterfaceStyle == .dark ? .white : .black
    }
    
    let navBarAppearance = UINavigationBar.appearance()
    navBarAppearance.largeTitleTextAttributes = [.foregroundColor: dynamicTextColor]
    navBarAppearance.titleTextAttributes = [.foregroundColor: dynamicTextColor]
}

系统会根据当前的界面风格(light/dark)自动选择对应的颜色,无需额外监听模式变化。

方案二:纯SwiftUI原生实现

放弃使用UINavigationBar.appearance(),改用SwiftUI的toolbar自定义导航栏标题,直接结合colorScheme环境变量控制颜色:

首先在视图中注入colorScheme环境变量:

@Environment(\.colorScheme) private var colorScheme

然后自定义导航栏标题:

.navigationBarTitleDisplayMode(.large)
.toolbar {
    // 自定义主标题
    ToolbarItem(placement: .principal) {
        Text("你的标题")
            .font(.largeTitle.bold())
            .foregroundColor(colorScheme == .dark ? .white : .black)
    }
    // 保留你的右侧按钮
    ToolbarItem(placement: .navigationBarTrailing) {
        Button {
            showingAddView.toggle()
        } label: {
            Label("Hinzufügen", systemImage: "plus.circle")
                .foregroundColor(colorScheme == .dark ? .white : .black)
        }
    }
}

这种方式完全遵循SwiftUI的响应式设计,颜色会随着colorScheme的变化自动更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 07:05:24