返回

SwiftUI 极简教程 19:滑动卡片效果的终极指南(下)

IOS

回顾:前篇内容

在上篇教程中,我们了解了如何使用基本的 DragGesture 手势和 withAnimation 函数实现卡片滑动效果的基础知识。在本篇教程中,我们将深入研究更高级的技术,以完善我们的滑动卡片功能。

高级手势:SimultaneousGestureCombiner

SimultaneousGestureCombiner 允许我们同时处理多个手势。这对于创建复杂的手势交互非常有用,例如允许用户同时拖动并旋转卡片。

let simultaneousGesture = SimultaneousGestureCombiner.and(
    DragGesture(),
    RotationGesture()
)

动画:SpringAnimation

SpringAnimation 提供了弹簧效果,使其在用户释放手指时让卡片回弹到位。

withAnimation(.spring()) {
    // 更新卡片位置和旋转角度
}

实现滑动卡片

现在,让我们将这些高级技术结合起来,实现一个功能齐全的滑动卡片:

struct SwipeCard: View {
    @State private var offset = CGSize.zero
    @State private var angle = Angle.zero

    var body: some View {
        ZStack {
            // 卡片视图
            RoundedRectangle(cornerRadius: 16)
                .fill(Color.white)
                .frame(width: 300, height: 300)
                .offset(offset)
                .rotationEffect(angle)
                .gesture(
                    SimultaneousGestureCombiner.and(
                        DragGesture()
                            .onChanged { value in
                                // 更新偏移量
                                self.offset = value.translation
                            }
                            .onEnded { value in
                                // 添加弹簧动画
                                withAnimation(.spring()) {
                                    self.offset = .zero
                                }
                            },
                        RotationGesture()
                            .onChanged { value in
                                // 更新旋转角度
                                self.angle = value
                            }
                            .onEnded { value in
                                // 添加弹簧动画
                                withAnimation(.spring()) {
                                    self.angle = .zero
                                }
                            }
                    )
                )
        }
    }
}

使用这个滑动卡片

要使用这个滑动卡片,只需在你的 SwiftUI 视图中添加以下代码:

struct ContentView: View {
    var body: some View {
        SwipeCard()
    }
}

结论

本教程演示了如何使用高级手势和动画技术在 SwiftUI 中创建滑动卡片效果。通过结合 SimultaneousGestureCombinerSpringAnimation,我们创建了一个流畅、响应迅速且令人印象深刻的交互式 UI 元素。