0

I am new to swiftUI, I have 2 views. I want that in AddTodoView using the ColorPicker I select a color, and in the ContentView this color is displayed in the background.

ContentView .background(AddTodoView().backgroundColor)

AddTodoView @State var backgroundColor = Color(.systemBackground) ColorPicker("Choosing a background color", selection: $backgroundColor)

  • Related: https://stackoverflow.com/q/57415086/3151675 – Tamás Sengel Aug 01 '21 at 17:21
  • It is somehow difficult for my task –  Aug 01 '21 at 17:27
  • Welcome to SO - Please take the [tour](https://stackoverflow.com/tour) and read [How to Ask](https://stackoverflow.com/help/how-to-ask) to improve, edit and format your questions. Without a [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) it is impossible to help you troubleshoot. – lorem ipsum Aug 01 '21 at 17:44

1 Answers1

1

You can share data between views using a @Binding. Right now, by calling AddTodoView().backgroundColor, you're creating a new instance of AddTodoView, whereas you actually want to reference the value from the same view that exists in your hierarchy.

struct ContentView : View {
    @State var backgroundColor : Color = Color(.systemBackground)
    
    var body: some View {
        ZStack {
            backgroundColor //I'm using it in a ZStack, but you could also attach .background(backgroundColor) to any element in the hierarchy
            AddTodoView(backgroundColor: $backgroundColor)
        }
    }
}

struct AddTodoView : View {
    @Binding var backgroundColor: Color
    
    var body: some View {
        ColorPicker("Choose a color", selection: $backgroundColor)
    }
}
jnpdx
  • 45,847
  • 6
  • 64
  • 94
  • What value to write in AddTodoView(backgroundColor: ***) ```struct AddTodoView_Previews: PreviewProvider { static var previews: some View { AddTodoView(backgroundColor: ) } }``` –  Aug 01 '21 at 17:55
  • You could use `.constant(Color(.systemBackground))` or `.constant(Color.white)` or any `Color` you want wrapped in `.constant()` – jnpdx Aug 01 '21 at 17:57