swift - 在 SwiftUI 中点击 MKMapView
问题描述
我在 SwiftUI 应用程序中有一张地图。它正在发挥作用;但现在我希望能够点击它并知道点击的纬度和经度。这是当前代码:
import SwiftUI
import MapKit
struct MapView: UIViewRepresentable {
@Binding var centerCoordinate: CLLocationCoordinate2D
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView()
mapView.delegate = context.coordinator
let gRecognizer = UITapGestureRecognizer(target: context.coordinator,
action: #selector(Coordinator.tapHandler(_:)))
mapView.addGestureRecognizer(gRecognizer)
return mapView
}
func updateUIView(_ view: MKMapView, context: Context) {
//print(#function)
}
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
class Coordinator: NSObject, MKMapViewDelegate {
var parent: MapView
init(_ parent: MapView) {
self.parent = parent
}
let gRecognizer = UITapGestureRecognizer(target: self,
action: #selector(tapHandler(_:)))
@objc func tapHandler(_ gesture: UITapGestureRecognizer) {
print(#function)
.... get useful information here ...
}
}
}
在这种状态下,当我点击时我可以看到,但我没有得到我需要的信息(即点击的坐标)。在网上搜索后,我尝试了一些代码的变体。在这一点上,它还没有工作。非常欢迎任何有关前进道路的相关提示。
解决方案
我有类似的情况,这就是我所做的。我制作了 Coordinator UIGestureRecognizerDelegate,并确保将 gRecognizer 委托设置为它,并将其添加到地图中。就像是:
struct MapView: UIViewRepresentable {
@Binding var centerCoordinate: CLLocationCoordinate2D
let mapView = MKMapView()
func makeUIView(context: Context) -> MKMapView {
mapView.delegate = context.coordinator
return mapView
}
func updateUIView(_ view: MKMapView, context: Context) {
//print(#function)
}
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
class Coordinator: NSObject, MKMapViewDelegate, UIGestureRecognizerDelegate {
var parent: MapView
var gRecognizer = UITapGestureRecognizer()
init(_ parent: MapView) {
self.parent = parent
super.init()
self.gRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapHandler))
self.gRecognizer.delegate = self
self.parent.mapView.addGestureRecognizer(gRecognizer)
}
@objc func tapHandler(_ gesture: UITapGestureRecognizer) {
// position on the screen, CGPoint
let location = gRecognizer.location(in: self.parent.mapView)
// position on the map, CLLocationCoordinate2D
let coordinate = self.parent.mapView.convert(location, toCoordinateFrom: self.parent.mapView)
}
}
}
推荐阅读
- amazon-web-services - 使用 Terraform 在 AWS Ampify 上添加存储库分支并配置构建
- c# - 将字符串解析为 Int C#
- angular - Angular SSR - 在浏览器和服务器中使用 performance.now()
- r - 有什么办法可以同时打开多个 R markdown 文件并编织它们?
- java - 在数组中查找目标总和的对
- r - R FlexmixNL 包中的数据太长错误
- node.js - 有没有一种跨平台的方式来获取 Node.js 中父进程的名称?
- javascript - $.each 将循环的结果放在
我在做一个 ajax 调用并从 DB 中得到很多结果,然后我使用 jquery 来循环它们并做一个简单的表。问题是循环将结果放在外面
<table>
和外面<tbody>
,并在所有内容的顶部创建一个 tbody 。我知道当前结果是静态的,仅用于测试,而且我知道 JS 是同步的,所以我不明白问题出在哪里。我的代码:$('#' + id).a
- flutter - 选择时使用 fixedCircle 的 ConvexAppBar 不会更改非圆形选项卡的活动颜色
- python - 如何在 Python Pandas 的列中显示超过 2 个值的行?