Home > Back-end >  Trying to change the accent color of the app using @AppStorage doesn't make any changes until a
Trying to change the accent color of the app using @AppStorage doesn't make any changes until a

Time:12-16

I am trying to create some functionality where the accent color of the app changes depending on what the user chose using a color picker.

This is my code:

import SwiftUI

class ColorStorage: ObservableObject {
    @AppStorage("someColor") var someColor: Color = .blue
}

@main
struct PocketIslamApp: App {
    var selectedColor = ColorStorage()
    
    var body: some Scene {
        WindowGroup {
            TesterView()
                .environmentObject(selectedColor)
                .accentColor(selectedColor.someColor)
        }
    }
}

struct TesterView: View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: TesterView2()) {
                Text("Click Me")
            }
        }
    }
}

struct TesterView2: View {
    
    @EnvironmentObject var selectedColor: ColorStorage
    
    var body: some View {
        ColorPicker("Pick a Color", selection: $selectedColor.someColor)
    }
}

FYI I am able to use Color with @AppStorage because of an extension I pulled from this Stack Overflow answer.

The idea for this project is that I want the accent color of the entire app to be changed immediately after the user chooses a color from the ColorPicker. But this does not happen. Instead, it changes only after I shut off the app and start it up again. How can I make this change instantaneous?

Any help would be greatly appreciated.

CodePudding user response:

To make this work properly with SwiftUI and an environment object you need to declare the selectedColor as a @StateObject

@StateObject var selectedColor = ColorStorage()
  • Related