My goal is to do this with multiple buttons but on click all the buttons change color.
Yes, because they are all using the same variable (number
) to determine the color:
.buttonStyle(ChangeColorButton(number: number))
I'm not entirely clear what it is you are trying to achieve, but if you want the color of the Button
s to be independent of one another, you need to track their state independently.
Something like this, perhaps:
struct ColoredButtons: View {
let buttons = [
["7", "8", "9"],
["4", "5", "6"],
["1", "2", "3"]
]
@State private var colors = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
var body: some View {
let _ = Self._printChanges()
VStack {
ForEach(buttons.indices, id: \.self) { row in
HStack {
ForEach(buttons[row].indices, id: \.self) { col in
Button("\(buttons[row][col])") {
changeColor(row, col)
}
.font(.system(size: 32))
.frame(width: 80, height: 80)
.buttonStyle(ChangeColorButton(number: colors[row][col]))
}
}
}
}
}
func changeColor(_ row: Int, _ col: Int) {
let currentColor = colors[row][col]
if currentColor == 3 {
colors[row][col] = 0
} else {
colors[row][col] = currentColor + 1
}
}
struct ChangeColorButton: ButtonStyle {
let colors: [Color] = [.gray, .green, .red, .yellow]
let number: Int
func makeBody(configuration: Configuration) -> some View {
configuration.label
.frame(width: 25, height: 25, alignment: .center)
.padding()
.background(colors[number])
}
}
}