SwiftUI双指点击手势检测实现求助:编译报错问题解决
解决SwiftUI双指点击检测的编译错误
你遇到的编译错误是因为UIViewRepresentableContext是泛型类型,必须指定对应的UIViewRepresentable实现类作为类型参数,原代码中缺少这个参数导致报错。
以下是修正后的完整可编译代码,包含双指点击检测的完整实现:
struct DoubleTapView: UIViewRepresentable { // 定义点击回调闭包 var onDoubleTap: () -> Void func makeUIView(context: UIViewRepresentableContext<DoubleTapView>) -> UIView { let view = UIView() let doubleTapGesture = UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.handleDoubleTap)) // 设置双指触发 doubleTapGesture.numberOfTouchesRequired = 2 // 可选:设置点击次数,1为双指单击,2为双指双击 doubleTapGesture.numberOfTapsRequired = 1 view.addGestureRecognizer(doubleTapGesture) return view } func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<DoubleTapView>) {} // 创建协调器处理手势事件 func makeCoordinator() -> Coordinator { Coordinator(onTap: onDoubleTap) } class Coordinator: NSObject { private let onTap: () -> Void init(onTap: @escaping () -> Void) { self.onTap = onTap } @objc func handleDoubleTap(sender: UITapGestureRecognizer) { // 确保手势结束时触发回调 if sender.state == .ended { onTap() } } } }
使用示例
在SwiftUI视图中直接调用这个自定义View:
struct ContentView: View { var body: some View { DoubleTapView { print("双指点击触发!") } .frame(maxWidth: .infinity, maxHeight: .infinity) } }
内容的提问来源于stack exchange,提问作者dor sahar
相关产品推荐
相关产品推荐

