从 mapAnnotaion 获取对象并使用 segue 传递它

getting the object from mapAnnotaion and passing it with segue

我有一个显示条形图的应用程序,以及一个包含每个条形图详细信息的信息栏视图控制器。

我在地图上显示带有注释的位置,当我按下一个注释以使用该数据转至 infoVc 时。

我该怎么做?

我正在使用 prepare 和 perform with segue,并尝试将注释转换为 Bar 对象,但没有成功...

准备--

    let segueMapToInfo = "mapToDetail"
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == segueMapToInfo {
            let destVC = segue.destination as! InfoViewController
            destVC.infoBar = ???
        }
    }

执行 --

func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
    let bar = view.annotation as? Bar
    print("sucess")
    performSegue(withIdentifier: segueMapToInfo, sender: bar)
}

在我的 infoVC 中,我有一个 infoBar 变量来捕获数据

注意 - 当我尝试传输硬编码条形图(我创建的示例条形图)时它起作用了,所以问题在于将注释转换为通用条形图对象

您可以使用从 didSelectAnnotationView 中选择的注释,然后将该注释存储到实例变量,然后在您的准备中使用注释(对于 segue: 方法。

var getSelectedAnnotation: Bar?

 func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    if let getBar = view.annotation as? Bar{
     getSelectedAnnotation = getBar
     print("sucess")
     performSegue(withIdentifier: segueMapToInfo, sender: self)
    }
}

   let segueMapToInfo = "mapToDetail"
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == segueMapToInfo {
            let destVC = segue.destination as! InfoViewController
            destVC.infoBar = getSelectedAnnotation
        }
    }