3

I've integrated themes into my app using this This idea

I have an EnvironmentKey that is used throughout the app:

private struct ColorThemeKey: EnvironmentKey {
    static let defaultValue = Color.Theme.system
//    static let defaultValue = Color.Theme.night
}

extension EnvironmentValues {
    var preferredColorTheme: Color.Theme {
        get {
            return self[ColorThemeKey.self]
        }
        set {
            self[ColorThemeKey.self] = newValue
        }
    }
}

It works great by changing the default value and relaunching the app.

I'm new to EnvironmentKey's and i'm struggling to figure out how to allow the user to change this. I have a list of available themes, but how to I overwrite the current them and set a new one that will take over immediately?

When I try to set a new theme like this, it tells me it's get only:

let newTheme = theme.theme
Environment(\.preferredColorTheme).wrappedValue = newTheme
Darren
  • 10,182
  • 20
  • 95
  • 162
  • 1
    You change it in view, consider this as example https://stackoverflow.com/a/61847419/12299030. – Asperi Apr 02 '22 at 16:50
  • So I have the theme as a `State` in the root view and inject it using `.environment` but when several views down how do I change the state in the root for it to change? – Darren Apr 02 '22 at 16:58
  • 1
    I've created a Themes singleton and added it as an `envrionmentObject` and have it working. So I think I misunderstand how the `EnvironmentValues` is used. – Darren Apr 02 '22 at 18:14

0 Answers0