State Variables and ForEach Swift

テッド

I'm trying to build a simple view in swiftUI with a foreach loop that contains three buttons, and animates these buttons based on a state variable. The problem is, when one button is pressed, all of them animate. I've been working on it for a good few hours but I can't figure out a way to have only one of the buttons in the view animate when it is pressed without just not using a foreach loop and just making three different state variables for three different CardView views. Here is the code for reference:

struct CardView: View {
    var flipped:Bool

    var body: some View {
        VStack {

            Image(flipped ? "cardFront" : "cardBack").renderingMode(.original)
                .resizable()
                .scaledToFit()
                .frame(height: 200)
                .rotation3DEffect(Angle(degrees: flipped ? 0 : 180), axis: (x: 0, y: 1, z: 0))
                .opacity(1)
            Text("Flip").padding()
        }
    }
}


struct ContentView: View {

    @State var isFlipped = false


    var body: some View {

        HStack {
            ForEach(0..<3) {number in
                Button(action: {
                    withAnimation(.spring()) {
                        self.isFlipped.toggle()
                    }
                }) {
                    CardView(flipped: self.isFlipped)
                }
            }
        }
    }
}

Would be very grateful for any pointers as I'm pretty new to all of this. I'd really like to figure out how to make this work in a foreach loop without the aforementioned work around.

krjw

Put the @State variable and the Button in the CardView. Here is a basic example:

I needed to use a Rectangle since I didn't have the images you used.

struct CardView: View {

    @State var isFlipped = false

    var body: some View {
        VStack {
            Rectangle()
                .foregroundColor(self.isFlipped ? Color.blue : Color.red)
                .frame(width: 100, height: 200)
                .rotation3DEffect(Angle(degrees: self.isFlipped ? 0 : 180), axis: (x: 0, y: 1, z: 0))
                .opacity(1)
            Button(action: {
                withAnimation(.spring()) {
                    self.isFlipped.toggle()
                }
            }) {
                Text("Flip")
            }
        }
    }
}


struct ContentView: View {
    var body: some View {

        HStack {
            ForEach(0..<3) {number in
                CardView()
            }
        }
    }
}

I hope this helps!

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive