[Swift] Save Color to User Defaults in Swift UI (memo)

Implementation note to save Color in UserDefaults when using Swift UI

environment

Implementation example

Save as Color → cgColor → RGB value

        let userDefaults = UserDefaults.standard
        let color = Color.orange
        if let components = color.cgColor?.components {
            userDefaults.setValue(components[0], forKey: "RColor")
            userDefaults.setValue(components[1], forKey: "GColor")
            userDefaults.setValue(components[2], forKey: "BColor")
        }

When using, extract the value as Double type from UserDefaults and Just generate Color from RGB as below

let color = Color(.sRGB, red: RColor, green: GColor, blue: BColor, opacity: 1.0)

Remarks

The app has been released! Please install it if you like. Toranpo

I started Twitter! Please follow me if you like. @yajima_tohshu

Recommended Posts

[Swift] Save Color to User Defaults in Swift UI (memo)
[swift5] How to specify color in hexadecimal
SKStoreReviewController implementation memo in Swift UI of iOS14
[Swift] Use UserDefaults to save data in the app
Photo library in Swift UI
How to change BackgroundColor etc. of NavigationBar in Swift UI
Create Master Detail in Swift UI
Implementing side menus in Swift UI
Try to display a slightly rich Webview in Swift UI using UIViewRepresentable
Customize View with View Modifier in Swift UI
Shorten the UUID to base64 in Swift.
[Swift] How to fix Label in UIPickerView
How to overwrite Firebase data in Swift
How to get the ID of a user authenticated with Firebase in Swift
How to fix a crash when deleting Realm data in Swift UI List
(Memo) How to solve dummy output in Ubuntu 20.04
How to color code console output in Eclipse
How to add sound in the app (swift)
[Swift UI] How to disable ScrollsToTop of ScrollView
How to execute tasks in parallel in Swift in Swift Package