从已点击的 mapView MKAnnotiation 通过 Segue 传递数据

Passing Data over Segue From a mapView MKAnnotiation that has been tapped

我正在尝试通过使用 calloutAccessoryControlTapped 控件点击 MkAnnotation 标注创建的 segue 传递数据。我想转到 EventViewController 并制作一个屏幕,其中包含有关所选 MkAnnotation 的更多信息。

我尝试了多种不同的方法,包括创建自定义 class 并尝试发送它。 segue 正确发生但没有数据传递到我的第二个 UIViewController (eventViewController)。

我假设我每次都做错了事,但我发现很难调试代码,因为我将数据分配给变量的点也是 segue 的触发点。

即我假设数据根本没有被分配,但是 "selectedAnnotation" 变量被正确传递但显然很难说。

    override func prepare(for segue: UIStoryboardSegue, sender: (Any)?) {
        if segue.identifier == "goToEventScreen" {
            selectedAnnotation = mapView.selectedAnnotations.lastObject as? MKAnnotation
            let destinationVC = segue.destination as! EventViewController
            destinationVC.points = selectedAnnotation
        }
    }
}
'''
extension ViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView,
                 calloutAccessoryControlTapped control: UIControl){
        performSegue(withIdentifier: "goToEventScreen", sender: self)
    }
}

提前致谢。

您需要在委托方法中将您的 annotationView 设置为 performSegue 方法的发送者。

extension ViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
        performSegue(withIdentifier: "goToEventScreen", sender: view)
    }
}

然后准备segue方法:

override func prepare(for segue: UIStoryboardSegue, sender: (Any)?) {
    if segue.identifier == "goToEventScreen" {
        if let annotationView = sender as? MKAnnotationView {
            selectedAnnotation = annotationView.annotation
            let destinationVC = segue.destination as! EventViewController
            destinationVC.points = selectedAnnotation
        }
    }
}

您所做的是从选定的 annotationView 中获取注释并将其分配给目标 VC 的点。