简体   繁体   English

SwiftUI 如何实现暗模式切换和刷新所有视图

[英]SwiftUI How to implement dark mode toggle and refresh all views

I'd like to implement a simple toggle to manually switch between dark and light modes.我想实现一个简单的切换来手动在暗模式和亮模式之间切换。 However, I don't know how to make my app refresh (redraw all windows) after I switch the toggle.但是,我不知道如何在切换切换后让我的应用程序刷新(重绘所有窗口)。

So far I found these answers Manually set light/dark mode in SwiftUI and Implement dark mode switch in SwiftUI App .到目前为止,我找到了这些答案Manually set light/dark mode in SwiftUI and Implement dark mode switch in SwiftUI App

But both these solutions use SceneDelegate.shared which is not recommended according to this answer .但是这两种解决方案都使用SceneDelegate.shared根据这个答案不推荐。

var isDark: Bool = true {
    didSet { SceneDelegate.shared?.window!.overrideUserInterfaceStyle = isDark ? .dark : .light }
}

Is there really no other option to implement this?真的没有其他选择来实现这一点吗? I tried adding @Environment variable but it works only once when the application starts.我尝试添加@Environment变量,但它只在应用程序启动时工作一次。 And I need my app to update the color scheme on toggle change.而且我需要我的应用程序在切换更改时更新配色方案。

.environment(\.colorScheme, settings.isDarkMode ? .dark : .light)

This is my toggle:这是我的切换:

struct SettingsView: View {
    var body: some View {
        Toggle(isOn: $settings.isDarkMode) {
            Text("Night mode")
        }
    }
}

In my model I have this variable:在我的 model 我有这个变量:

@UserDefaultsBacked(key: UserDefaults.Keys.Settings.darkMode, defaultValue: false)
var isDarkMode: Bool

Just add .colorScheme to your top View and add a color scheme variable ( @State , @Binding , etc.).只需将.colorScheme添加到您的顶部视图并添加一个配色方案变量( @State@Binding等)。 Whenever the variable changes the view (and children) update automatically.每当变量改变视图(和孩子)自动更新。

struct ContentView: View {
    @State var theColorScheme: ColorScheme = .dark

    func toggleColorScheme() {
        theColorScheme = (theColorScheme == .dark) ? .light : .dark
    }

    var body: some View {
        VStack { // or any other View
            Button(action: self.toggleColorScheme) {
                Text("Toggle")
            }
        }   .colorScheme(theColorScheme)
    }
}

This solution works for me这个解决方案对我有用

Step 1:步骤1:

struct AppName: App {

@AppStorage("appTheme") private var isDarkModeOn = false

var body: some Scene {
    WindowGroup {
        MainTabView()
            .preferredColorScheme(isDarkModeOn ? .dark : .light)
    }
}}

Step 2:第2步:

Then you change this variable via button click然后通过单击按钮更改此变量

var body: some View {

@AppStorage("appTheme") private var isDarkModeOn = false

    VStack {
            Button {
                self.isDarkMode.toggle()
            } label: {
                Image("dark_mode_icon")
            }
      }}





         

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM