2

单击地图上的图钉时,我一直在尝试调用函数。我的地图上有大约十个图钉,那么如何确定按下了哪个图钉并拥有 MKPointAnnotation 包含的所有数据?

如何将每个注释添加到地图中:

 let map = MKMapView(frame: .zero)
 let annotation = MKPointAnnotation()

 annotation.coordinate = donator.coordinates
 annotation.title = donator.name
 annotation.subtitle = donator.car
 map.addAnnotation(annotation)

谢谢!

4

1 回答 1

1

假设您将您的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 { ... }
}
于 2020-11-22T07:01:59.773 回答