SwiftUI 暗/亮模式通过@AppStorage 改变

SwiftUI dark / light mode change with @AppStorage

我正在尝试使用 3 个选项更改应用程序的主题:默认、深色、浅色。然后视图跳转到主视图,但我想留在设置视图上。

struct SettingsView: View {
...
@State var colors = ["Alapértelmezett", "Sötét", "Világos"] //Default, Dark, Light
@AppStorage("colorIndex") var colorIndex: Int = 0
...
var body: some View {
...
Picker(selection: $colorIndex, label: Text("Megjelenés")) { //Color
                            ForEach(0 ..< colors.count) {
                                Text(self.[[=10=]])
                            }
                            
                        }

...

在“MyApp.swift”中:

@main
struct MyApp: App {

        
    @AppStorage("colorIndex") var colorIndex: Int = 0
    
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    var body: some Scene {
        WindowGroup {

            if colorIndex == 1 {
                
                ContentView().environment(\.colorScheme, .dark)
            }
            else if colorIndex == 2 {
                ContentView().environment(\.colorScheme, .light)
            }
            else {
                ContentView()
            }
                

        }
        
    }

}

你为什么要让应用负责深色和浅色主题,我认为你应该让系统来处理这个。除此之外,检查你的功能。如果您调用 ContentView,则显示它是有意义的。

如果您不希望系统处理此问题。检查这个 post 也许这对你有帮助