Home > database >  How do I do a 3D rotation animation with 2 views?
How do I do a 3D rotation animation with 2 views?

Time:11-14

I have 2 views: an image and a shape that fills the image in. Once I flip the shape the image is supposed to show. Here is my code;

struct DogCard: View {
    @State var animationAmount = 0.0
    @State var isFaceUp: Bool = false
    
    var card: MemoryGame.Card
    var body: some View {
        ZStack{
            let shape = RoundedRectangle(cornerRadius: 10)
            if card.isFaceUp {
                shape.stroke(lineWidth: 3).foregroundColor(.blue)
                Image(card.content).resizable().scaledToFit().padding()
                
            }
            else {
                shape.fill().foregroundColor(.blue)
            }
            
        }
        .rotation3DEffect(.degrees(animationAmount), axis: (x: 0, y: 1, z: 0))
        .onTapGesture {
            withAnimation {
                animationAmount  = 180
                isFaceUp.toggle()
            }
        }
    }
}

I am trying to have the image show up once the shape is tapped on and made to flip.

^ the shape flips over when u tap on it (no image is shown - error)

CodePudding user response:

In withAnimation, use card.isFaceUp.toggle() instead of isFaceUp.toggle(). Try this:

    @State var card: MemoryGame.Card  // <-- here, @Binding if need be
    // ....

    .onTapGesture {
        withAnimation {
            animationAmount  = 180
            card.isFaceUp.toggle()   // <-- here
        }
    }

The reason you are not getting an Image with your code is because your if card.isFaceUp {...} is not based on your var isFaceUp, it is based on card.isFaceUp. So toggle that.

  • Related