HomeiOS Developmentios - Find out how to implement Shade Theme switcher that works...

ios – Find out how to implement Shade Theme switcher that works throughout entire app in SwiftUI?


I’m making an attempt to implement a colour theme change from a selected view in my app.
Right here’s what I’ve to date:

enum Theme: CaseIterable, Identifiable, Equatable {
    var id: Self { self }
    case normal
    case inexperienced
   

    var accent: Shade {
        change self {
            case .normal:
            return Shade.accent
        case .inexperienced:
            return Shade.inexperienced
    }

    var description: String {
        change self {
            case .normal:
        "Normal"
            case .inexperienced:
        "Inexperienced"
    }
}
}

and a easy supervisor:

@Observable
ultimate class ThemeManager {
    var theme: Theme = .normal
    var accent: Shade { theme.accent }
    var description: String { theme.description }
}

I add it to setting values:

extension EnvironmentValues {
    @Entry var themeManager = ThemeManager()
}

In my primary MyApp: App struct I’ve this:

@State personal var theme = ThemeManager()

and I add it to setting like this:

 ContentView().setting(themeManager)

Then in my opinion (Settings), I do that:

@Setting(.themeManager) personal var themeManager

and use it like this:

personal extension SettingsView {
    @ViewBuilder
    var check: some View {
        @Bindable var themeManager = themeManager
        Part {
            Picker("", choice: $themeManager.theme) {
                ForEach(Theme.allCases) { themeEnum in
                    Textual content(themeEnum.description).tag(themeEnum.id)
                        .foregroundStyle(themeEnum.accent)
                }
            }
            .onChange(of: themeManager.theme, { oldValue, newValue in
                print("Theme supervisor outdated worth (oldValue), newValue (newValue)")
            })
            .pickerStyle(.inline)
            .labelsHidden()
        } header: {
            Textual content("Theme")
        }
    }
}

So, I’ve three tabs, and one among them is that this SettingsView the place I’m making an attempt to vary the theme.
The problem is that the theme change impacts all views inside SettingsView, however the different tabs and their views stay unaffected.

In all different tabs/view, I seize supervisor like this:

@Setting(.themeManager) personal var themeManager

Am I lacking one thing? What’s the correct approach to implement this in order that the theme change applies globally?

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments