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

问题描述 投票:0回答:1

SwiftUI MagnificationGestureDragGesture具有.onChanged.onEnded API,但是像UIKit中一样,手势开始时无需检查。我认为可以这样做的几种方法:

  • onChanged中的[.$gestureStarted bool,然后在.onEnded中将其设置回false
  • 轻按使用手势序列。

我是否缺少一些首选的方法?要检查似乎是很自然的事情。

swiftui gesture-recognition
1个回答
0
投票

有一个特殊的@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")
            }
        )
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.