如何调用函数或判断是否在 MKMapView SwiftUI 上单击了 MKPointAnnotation
How to call a function or tell if a MKPointAnnotation is clicked on a MKMapView SwiftUI
我一直在尝试在点击地图上的图钉时调用一个函数。我的地图上大约有十个图钉,那么我如何确定按下了哪个图钉并获得 MKPointAnnotation 包含的所有数据?
如何将每个注释添加到地图:
let map = MKMapView(frame: .zero)
let annotation = MKPointAnnotation()
annotation.coordinate = donator.coordinates
annotation.title = donator.name
annotation.subtitle = donator.car
map.addAnnotation(annotation)
谢谢!
假设您将 MKMapView
包装在 UIViewRepresentable
结构中,使用 MKMapViewDelegate
协议添加协调器以监听地图上的变化:
//Inside your UIViewRepresentable struct
func makeCoordinator() -> Coordinator {
Coordinator()
}
class Coordinator: NSObject, MKMapViewDelegate {
//Delegate function to listen for annotation selection on your map
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if let annotation = view.annotation {
//Process your annotation here
}
}
}
有几个教程介绍如何在 SwiftUI 中包含 MKMapView 并使用委托通过 UIViewRepresentable
和协调器访问 MKMapViewDelegate
函数。
按照我的建议,您之前的代码将如下所示:
struct MapKitView: UIViewRepresentable {
typealias Context = UIViewRepresentableContext<MapKitView>
func makeUIView(context: Context) -> MKMapView {
let map = MKMapView()
map.delegate = context.coordinator
let annotation = MKPointAnnotation()
annotation.coordinate = donator.coordinates
annotation.title = donator.name
annotation.subtitle = donator.car
map.addAnnotation(annotation)
return map
}
//Coordinator code
func makeCoordinator() -> Coordinator { ... }
}
我一直在尝试在点击地图上的图钉时调用一个函数。我的地图上大约有十个图钉,那么我如何确定按下了哪个图钉并获得 MKPointAnnotation 包含的所有数据?
如何将每个注释添加到地图:
let map = MKMapView(frame: .zero)
let annotation = MKPointAnnotation()
annotation.coordinate = donator.coordinates
annotation.title = donator.name
annotation.subtitle = donator.car
map.addAnnotation(annotation)
谢谢!
假设您将 MKMapView
包装在 UIViewRepresentable
结构中,使用 MKMapViewDelegate
协议添加协调器以监听地图上的变化:
//Inside your UIViewRepresentable struct
func makeCoordinator() -> Coordinator {
Coordinator()
}
class Coordinator: NSObject, MKMapViewDelegate {
//Delegate function to listen for annotation selection on your map
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if let annotation = view.annotation {
//Process your annotation here
}
}
}
有几个教程介绍如何在 SwiftUI 中包含 MKMapView 并使用委托通过 UIViewRepresentable
和协调器访问 MKMapViewDelegate
函数。
按照我的建议,您之前的代码将如下所示:
struct MapKitView: UIViewRepresentable {
typealias Context = UIViewRepresentableContext<MapKitView>
func makeUIView(context: Context) -> MKMapView {
let map = MKMapView()
map.delegate = context.coordinator
let annotation = MKPointAnnotation()
annotation.coordinate = donator.coordinates
annotation.title = donator.name
annotation.subtitle = donator.car
map.addAnnotation(annotation)
return map
}
//Coordinator code
func makeCoordinator() -> Coordinator { ... }
}