Reputation:
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)
Upvotes: 0
Views: 396
Reputation: 52397
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)
}
}
Upvotes: 1