如何 运行 在 swiftui 手势识别器开始时编码

How to run code when swiftui gesture recognizers begin

SwiftUI MagnificationGestureDragGesture.onChanged.onEnded API,但没有像 UIKit 那样检查手势开始的时间。我想到了几种方法:

我是否遗漏了一些首选方法?想要检查似乎是很自然的事情。

有特殊的@GestureState,可用于此目的。所以,这是可能的方法

struct TestGestureBegin: View {

    enum Progress {
        case inactive
        case started
        case changed
    }
    @GestureState private var gestureState: Progress = .inactive // initial & reset value

    var body: some View {
        VStack {
            Text("Drag over me!")
        }
        .frame(width: 200, height: 200)
        .background(Color.yellow)
        .gesture(DragGesture(minimumDistance: 0)
            .updating($gestureState, body: { (value, state, transaction) in
                switch state {
                    case .inactive:
                        state = .started
                        print("> started")
                    case .started:
                        state = .changed
                        print(">> just changed")
                    case .changed:
                        print(">>> changing")
                }
            })
            .onEnded { value in
                print("x ended")
            }
        )
    }
}