The Util Designer
SwiftUI 實現卡片的翻轉
xcode 13.4.1, swift 5.5, iOS 15.4
2022-08-17
這篇主要是講述如何使用SwiftUI實現卡片的翻轉。
1. 先實現卡片的正面。
import SwiftUI

struct CardUp : View {
    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 10)
                .stroke(.orange, lineWidth: 5)
            Image(systemName: "suit.club.fill")
                .foregroundColor(.orange)
                .font(.largeTitle)
        }.background(.white)
    }
}


struct FlipExample : View {
    var body: some View {
        CardUp()
            .frame(width: 100, height: 180)
            .padding()
    }
}
2. 再實現卡片的反面。
import SwiftUI

struct CardDown : View {
    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 10)
                .fill(.orange)
            Circle()
                .inset(by: 10)
                .stroke(.white, lineWidth: 5)
        }.background(.white)
    }
}

struct FlipExample : View {
    var body: some View {
        CardDown()
            .frame(width: 100, height: 180)
            .padding()
    }
}
3. 最後使用rotation3DEffect以y軸為軸心實現翻轉卡片的動畫,以90度為界線,小於90度只顯示正面,大於90度只顯示反面,並以animation來控制角度變量,實現如下:
import SwiftUI

struct Card : View {
    @State var angle : Double = 0
    var body: some View {
        ZStack {
            CardUp()
                .rotation3DEffect(.degrees(angle), axis: (x: 0, y: 1, z: 0))
                .opacity(angle <= 90 ? 1.0 : 0.0)
                .onTapGesture {
                    angle = 180.0
                }
            CardDown()
                .rotation3DEffect(.degrees(angle), axis: (x: 0, y: 1, z: 0))
                .opacity(angle <= 90 ? 0.0 : 1.0)
                .onTapGesture {
                    angle = 0.0
                }
        }
        .frame(width: 100, height: 180)
        .animation(.linear(duration: 1), value: angle)
    }
}

struct FlipExample : View {
    var body: some View {
        Card()
    }
}