finn
finn

Reputation: 1063

How to detect when SwiftUI ColorPicker's color is updated?

I am working with SwiftUI and want to save a color to UserDefaults as soon as it is selected with the ColorPicker. What is the best way to do this?

struct CustomizeView: View {
    
    @State private var color: Color = Color.green
    
    var body: some View {
            ColorPicker("Select a color!", selection: $color, supportsOpacity: false)
        }.onAppear {
            guard let defaults = UserDefaults(suiteName: "...") else { return }
            color = Color(rgb: defaults.integer(forKey: "color"))
        }
    }

    // where do I call the saveColors() function?
    
    func saveColors() {
        guard let defaults = UserDefaults(suiteName: "...") else { return }
        defaults.set(color.rgb, forKey: "colorCancel")
        defaults.synchronize()
    }
}

(The rgb initializer for Color is custom and should not be relevant.)

Upvotes: 3

Views: 960

Answers (1)

Asperi
Asperi

Reputation: 257749

You can use onChange modifier, like

ColorPicker("Select a color!", selection: $color, supportsOpacity: false)
   .onChange(of: color) { _ in
      saveColors()
   }

Upvotes: 5

Related Questions