How to identify tapped button id in SwiftUI to make that button animated?

Viewed 137

I would like to animate a particular tapped button from the stack of buttons. Unfortunately withAnimation{} is applied to all the buttons created by FOREACH loop with no difference what button was actually tapped. Could you please recommend the right way to solve the issue? Here is my code:

import SwiftUI

struct ContentView: View {
    @State private var buttonBackgroundColorRed = false
    
    var body: some View {
        VStack {
            ForEach(1..<4) {num in
                Button {
                    withAnimation {
                        buttonBackgroundColorRed.toggle()
                    }
                } label: {
                    Text("Button \(num)")
                }
                .padding(10)
                .background(buttonBackgroundColorRed ? .red : .blue)
                .foregroundColor(.white)
                .padding()
            }
        }
    }
}
1 Answers

That is also possible, but it is simpler to extract ForEach row into standalone view with own state

struct ContentView: View {
    
    struct Row: View { 
      let num: Int

      @State private var buttonBackgroundColorRed = false

      var body: some View {
        Button {
            withAnimation {
                buttonBackgroundColorRed.toggle()
            }
        } label: {
            Text("Button \(num)")
        }
        .padding(10)
        .background(buttonBackgroundColorRed ? .red : .blue)
        .foregroundColor(.white)
        .padding()
      }
    }

    var body: some View {
        VStack {
            ForEach(1..<4) {num in
               Row(num: num)
            }
        }
    }
}
Related