假设您将您的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 并使用委托通过协调器访问MKMapViewDelegate
函数的教程。UIViewRepresentable
按照我的建议,您之前的代码如下所示:
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 { ... }
}