TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Update accentColor based on user selection in ColorPicker

Forums > SwiftUI

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!

3      

Hi @sabensm -- did you find a solution for this?

3      

If userPickedColor is really a UIColor, then you don't need to do:

Color(UIColor(userPickedColor))

You can just do:

Color(userPickedColor)

3      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.