2 秒后 swiftUI 自动延迟动画

swiftUI auto delay animation after 2sec

大家好,我正在学习 swiftUI,但我的项目遇到了一些问题。

我有一张主卡会轮换5张随机卡,加上卡的背面。底部的 5 个按钮代表随机的 5 张卡片。

当我按下 5 个按钮中的任何一个来旋转卡片时,我希望卡片在 2 秒后自动旋转回卡片背面

这是我的代码:

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()
    }
}

这里是一个按钮的演示

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