Search code examples
rotationswiftuiauto

swiftUI auto delay animation after 2sec


hi guys im learning swiftUI and i have some problem with my project.

i have one main card that will rotate 5 random card, plus the back of the card. and at the bottom 5 button that represent the 5 random card.

when i press any of the 5 buttons to rotate the card, i would like that the card rotate back automatically on the cardBack after 2 sec.

here is my code :

import SwiftUI


struct CardBack: View {
    var body: some View {

      Image("back_card")
        .resizable()
        .aspectRatio(contentMode: .fit)
        .frame(width: 250)
    }
}

struct ContentView: View {

   @State var flipped = false
   @State private var cardsFront = ["bigCard1", "bigCard2", "bigCard3", "bigCard4", "bigCard5" ]
   @State private var cardBack = "back_card"

    var body: some View {
        VStack {
            Spacer()
            ZStack {

            Image(flipped ? self.cardsFront.randomElement()! : self.cardBack)
              .resizable()
              .aspectRatio(contentMode: .fit)
              .frame(width: 250)
              .rotation3DEffect(Angle(degrees: flipped ? 180 : 0 ), axis: (x: 0, y: 1, z: 0))
            }

            Spacer()
            HStack {
                Button(action: {
                    withAnimation(.spring()) {
                        self.flipped.toggle()
                    }

                }) {
                    Image("circle")
                        .renderingMode(.original)
                }


                Button(action: {

                }) {
                    Image("plus")
                        .renderingMode(.original)
                }

                Button(action: {

                }) {
                    Image("wave")
                        .renderingMode(.original)
                }

                Button(action: {

                }) {
                    Image("square")
                        .renderingMode(.original)
                }

                Button(action: {

                }) {
                    Image("star")
                        .renderingMode(.original)
                }

            }
            Spacer()
        }

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


Solution

  • Here is a demo on one button

    Button(action: {
        withAnimation(.spring()) {
            self.flipped.toggle()
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            withAnimation(.spring()) {
                self.flipped.toggle()
            }
        }
    }) {
        Image("circle")
            .renderingMode(.original)
    }