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

我有.light和.dark主题。

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

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

            Group {
                ...
            } 
            .environment(\.colorScheme,theme) //This line
        }
 ...

如何动态更改应用程序主题(例如按钮操作)。 我试图在SceneDelegate中进行更改:

 let contentView = ContentView()
 contentView.environment(\.colorScheme,.dark) //Not work
erma001 回答:SwiftUI以编程方式更改颜色主题

有人告诉我,如果您将代码放在NavagationView中,则可以使用order_id | id =========+=== 2 | 1 来更改方案。

enviorment

var body: some View { NavigationView{ //Your view here }}

let contentView = ContentView()
 contentView.environment(\.colorScheme,.dark) //works now
,

如何添加反应性至:

 .environment(\.colorScheme,appState.theme))

我尝试使用该ObservableObject进行此操作,但未成功。

final class AppState: ObservableObject {
    /**
     OPTIONS
     */

    @Published var theme: ColorScheme = .light;
,

反应:

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

    } 
    .environment(\.colorScheme,appState.options.theme == .light ? .light : .dark)
本文链接:https://www.f2er.com/3108935.html

大家都在问