I'm trying to figure out how to pass a variable to a sub view.
To explain further.....
My main view has the code...
HStack {
Rectangle()
.fill(self.headerData.rectangle1Color)
.frame(width: 100, height: 100, alignment: .center)
ColorGrid()
}
As you can see, this is just a rectangle whose color is defined by the variable "rectangle1Color"
We then call ColorGrid() which is defined below...
struct ColorGrid: View {
@ObservedObject var headerData = HeaderData.shared
var body: some View {
HStack {
Button(action: {
changeColor(newColor: .blue)
}) {
Text("Blue").foregroundColor(.blue)
}
Button(action: {
changeColor(newColor: .red)
}) {
Text("Red").foregroundColor(.red)
}
Button(action: {
changeColor(newColor: .green)
}) {
Text("Green").foregroundColor(.green)
}
}// END OF HSTACK
}// END OF BODY
func changeColor(newColor: Color) {
self.headerData.rectangle1Color = newColor
}
}
This is a simple sub view with 3 buttons (red green blue)
Each button passes a color in the changeColor() func which in turn updates the value of rectangle1Color.
My Question Is...
If I want to use ColorGrid() in various different places, each controlling color of different variables - how can I specify in mainView which variable I want to adjust and then pass this to ColorGrid() and changeColor() accordingly??
I've tried various ideas but dont seem to be getting any closer