UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

button background colours

Forums > SwiftUI

I've study the solution from jan'21 where the buttoncolor change on click. My goal is to do this with multiple buttons but on click all the buttons change color. This is my code:

struct ContentView: View {

let buttons = [
["7", "8", "9"],
["4", "5", "6"],
["1", "2", "3"]
]

@State private var number: Int = 0
@State private var colors:[Int] = [0, 0, 0, 0]

var body: some View {
    Self._printChanges()
    return VStack {
        ForEach(buttons, id: \.self) { row in

        HStack {
                ForEach(row, id: \.self) { button in
                    Button("\(button)") {
                        changeColor()
                    }
                    .font(.system(size: 32))
                    .frame(width: 80, height: 80)
                    .buttonStyle(ChangeColorButton(number: number))
                }
            }
        }
    }
}

func changeColor() {
    if number == 3 {
        number = 0
    } else {
        number += 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])
    }
}

}

1      

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 Buttons 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])
        }
    }
}

1      

Thank you @roosterboy for your solution. I was struggle for months now to get this right but now I can go further with it. Greetings @PaddyTurtle

1      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.