swiftuicolor-pickerpublic-method

Is there a way to save a chosen color as a public variable?


I am implementing a Color Picker into my app. It works as intended, but i need to save the color as a public variable to use it in the next View.

I have coded the following:

struct Upload: View {
    @State var selectedColor = Color.black
        
    var body: some View {
        HStack(alignment: .center) {
            ColorPicker(
                "Pick a color", selection: $selectedColor
            ).frame(width: 150, height: 150)
            Spacer()
        }
    }
}


The only color-choosing method my app has been designed for is the eyedropper tool, so I am looking for a way to get the color the eyedropper tool chose and save it as a public variable.

Please keep in mind this is only the code for the Color Picker - there is code around it, such as Stacks above and a NavigationLink Button below.


Solution

  • You can use onChange(of:) to assign to a public variable when selectedColor is changed.

    Add this to your view:

    .onChange(of: selectedColor) { newValue in
        publicVariableColor = newValue
    }