0

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.

KodeKat
  • 15
  • 4

2 Answers2

0

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
}
Nhat Nguyen Duc
  • 432
  • 2
  • 10
-1

You are actually chosing and saving it. But to make it public, you need to do either of these two. You need to change @State var selectedColor = Color.black to @AppStorage("selectedColor") var selectedColor = Color.black. In the next view copy paste this code. Now the color will be saved to your apps data(Even if you re-open the app it doesn't go away.) and all views can use it(When you add the @AppStorage("selectedColor") var selectedColor = Color.black code).

If else like you don't want to save the color and only conected views will use it(I mean there is a NavigationLink to another view) use @Bindning. Here is how to use it.

struct download: View{
   @Bindning var selectedColor: Color
   var body: some View{
       selctedColor
   }
}

And here is how to use it in a NavigationLink:

NavigationLink("Download", destination: download(selectedColor: $selectedColor))

I hope this helped.