Learn Courses My Dashboard

Change appearance of buttons

Hello Community!
I have a ForEach Loop containing a variable number of buttons and I want that a button changes on tap, but without all the other buttons changing too.

So basically I need the code bellow to work for many buttons. Because I don’t know the number of buttons in advance and because the number can change, I can’t create an ,isOn variable" for every single one. (It also wouldn’t be a smooth solution).
Does anyone have an idea?

‘’’
@State private var isOn = false

var body: some View {

    Button(action: {
        isOn.toggle()
    }) {
        Text("No Sweats")
            .font(.largeTitle)
            .bold()
            .foregroundColor(isOn ? Color.red : Color.black)
    }
    .frame(width: 250, height: 60)
    .background(isOn ? Color.yellow : Color.red)
    .cornerRadius(10)
}

}

‘’’

Create a separate ButtonView that tracks its own state.

Something like this:

struct ButtonView: View {
    
    let title: String
    
    @State private var isOn = false
    
    var body: some View {
        Button {
            isOn.toggle()
        } label: {
            Text(title)
                .font(.largeTitle)
                .bold()
                .foregroundColor(isOn ? .red : .black)
        }
        .frame(width: 250, height: 60)
        .background(isOn ? Color.yellow : Color.red)
        .cornerRadius(10)
    }
}

struct ButtonContainer: View {
    
    let buttons: [String]
    
    var body: some View {
        VStack(spacing: 20) {
            ForEach(buttons, id: \.self) { title in
                ButtonView(title: title)
            }
        }
    }
}

Adjust to your specific needs.

Amazing!! It seems like such an obvious solution now… O: Thank you very much roosterboy