SwiftUI 以编程方式更改颜色主题

Tim*_*let 4 swiftui

我有 .light 和 .dark 主题。

在预览 (MyContainer_Previews) 中,我可以通过以下方式更改它们:

ForEach([.light,.dark], id: \.self) { theme in

            Group {
                ...
            } 
            .environment(\.colorScheme, theme) //This line
        }
 ...
Run Code Online (Sandbox Code Playgroud)

如何即时更改应用程序主题(fe 按钮操作)。我尝试在 SceneDelegate 中更改它:

 let contentView = ContentView()
 contentView.environment(\.colorScheme, .dark) //Not work
Run Code Online (Sandbox Code Playgroud)

Tim*_*let 5

反应式:

    return NavigationView {
        VStack(alignment: .trailing, spacing: 0) {
            ...
        }

    } 
    .environment(\.colorScheme, appState.options.theme == .light ? .light : .dark)
Run Code Online (Sandbox Code Playgroud)