iOS 26中Map组件绑定onTapGesture无响应问题及解决方案问询
解决iOS 26正式版中SwiftUI Map组件onTapGesture无响应的问题
在iOS 26正式版本中,为SwiftUI的Map组件添加onTapGesture手势后,该手势无法触发响应。点击示例代码中的Rectangle组件能正常输出日志,但点击Map组件无任何输出。相同代码在iOS 18.6中可正常运行,该问题已通过DTS编号859521022追踪,确认大概率是系统临时bug。
以下是几个可行的解决方案:
方案1:封装MKMapView自定义点击手势
通过原生MKMapView封装成SwiftUI组件,手动添加点击手势识别器,绕开SwiftUI层的手势冲突:
import SwiftUI import MapKit struct MapWithTap: UIViewRepresentable { var onTap: (CGPoint) -> Void func makeUIView(context: Context) -> MKMapView { let mapView = MKMapView() let tapGesture = UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.handleTap(_:))) mapView.addGestureRecognizer(tapGesture) return mapView } func updateUIView(_ uiView: MKMapView, context: Context) {} func makeCoordinator() -> Coordinator { Coordinator(self) } class Coordinator: NSObject { let parent: MapWithTap init(_ parent: MapWithTap) { self.parent = parent } @objc func handleTap(_ gesture: UITapGestureRecognizer) { let location = gesture.location(in: gesture.view) parent.onTap(location) } } } // 使用示例 struct ContentView: View { var merp: String { if #available(iOS 26.0, *) { "Hello, ios26" } else { "Hello, old man" } } var body: some View { VStack { Text(merp) Rectangle() .onTapGesture { location in print("wooo \(location.x) - \(location.y)") } MapWithTap { location in print("waaa \(location.x) - \(location.y)") } } .padding() } }
方案2:添加透明覆盖层接收手势
在Map上方叠加一个透明视图,将手势绑定到这个视图上,确保能接收点击事件:
struct ContentView: View { var merp: String { if #available(iOS 26.0, *) { "Hello, ios26" } else { "Hello, old man" } } var body: some View { VStack { Text(merp) Rectangle() .onTapGesture { location in print("wooo \(location.x) - \(location.y)") } ZStack { Map() Color.clear .contentShape(Rectangle()) .onTapGesture { location in print("waaa \(location.x) - \(location.y)") } } } .padding() } }
⚠️ 注意:该方案会拦截Map的原生交互(如缩放、拖拽),如果需要保留Map的完整交互能力,优先选择方案1。
内容的提问来源于stack exchange,提问作者Warren Burton
相关产品推荐
相关产品推荐

