Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to change dark to light theme and vice versa just like using a toggle programmitically in swift UI?

I did this but in this whole contentView is loading again and the app is coming to the start screen.

 struct ThemeChangeDemoApp: App {

     @AppStorage("theme") var currentThemeRawValue: String = "dark"
     var body: some Scene {
         WindowGroup {
             switch currentThemeRawValue {
             case Theme.dark.rawValue:
                 ContentView().environment(\.colorScheme, .dark)
             case Theme.light.rawValue:
                 ContentView().environment(\.colorScheme, .light)
             default:
                 ContentView().environment(\.colorScheme, .dark)
             }
         }
     }
 }

And from here I am changing the theme. I am saving the rawValue of the enum as "dark" or "light".

 struct Settings: View  {

     var body: some View {

                 Button {
                
                     let currentTheme = UserDefaultsHelper.getCurrentTheme()
                     switch currentTheme {
                     case Theme.dark.rawValue:
                         UserDefaultsHelper.saveTheme(theme: .light)
                     case Theme.light.rawValue:
                         UserDefaultsHelper.saveTheme(theme: .dark)
                     default:
                         UserDefaultsHelper.saveTheme(theme: .light)
                     }
                 } label: {
                Text("Toggle theme")
                 }

      }

 }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

WindowGroup {
  switch currentThemeRawValue {
  case Theme.dark.rawValue:
    ContentView().environment(\.colorScheme, .dark)
  case Theme.light.rawValue:
    ContentView().environment(\.colorScheme, .light)
  default:
    ContentView().environment(\.colorScheme, .dark)
  }
}

The switch statement means that SwiftUI is populating the view with conditional content, so it would rebuild the entire hierarchy if the value changes. You only really want to change the environment value itself, so something like this would probably be better:

WindowGroup {
  ContentView()
    .environment(\.colorScheme, currentThemeRawValue == "dark" ?? .dark : .light)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading