【问题标题】:How to call a function or tell if a MKPointAnnotation is clicked on a MKMapView SwiftUI如何调用函数或判断是否在 MKMapView SwiftUI 上单击了 MKPointAnnotation
【发布时间】:2020-11-22 05:05:06
【问题描述】:

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

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

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

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

谢谢!

【问题讨论】:

标签: ios swift mkmapview mkpointannotation


【解决方案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 并使用委托通过 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 { ... }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 2013-02-23
    • 2014-06-22
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多