I am trying to build a feature that allows a user to use a color picker to set their own custom accent color to be applied to the whole app. So far, my approach has been to get the value the user selects in the color picker and save it to UserDefaults
VStack {
ColorPicker("Set a custom color", selection: $userColor, supportsOpacity: false)
}.onChange(of: userColor, perform: { value in
UserDefaults.standard.setValue(userColor, forKey: "customColor")
})
}
I have an extension of UserDetaults to allow me to save as a UIColor. I am not sure how I could write an extension that would allow me to save as a SwiftUI Color as is not an NSObject.
Since I'm using new SwiftUI lifecycle and don't have an app or scene delegate, I am attempting to set the accent color in the Scene of the main App.Swift file. In my attempt I can't get the accent color to convert from a UIColor to a Color. However, I am not sure if this is even the appropriate way to handle this case.
var userPickedColor = UserDefaults.standard.color(forKey: "customColor") ?? UIColor(Color.accentColor)
var body: some Scene {
WindowGroup {
AppRootView().accentColor(Color(UIColor(userPickedColor))) // This throws the error Cannot convert value of type...
.environment(\.managedObjectContext, persistenceController.container.viewContext)
}
}
Am I on the right track here, or is there a better solution to allow for a user to set Accent Color that would apply to all views and modal popups in the app globally? Thanks!