首页 > 解决方案 > 从 mapAnotaion 获取对象并使用 segue 传递它

问题描述

我有一个显示条形图的应用程序和一个 infoBar 视图控制器,其中包含每个条形的详细信息。

我在地图上显示带有注释的位置,当我按下注释时想要使用该数据与 infoVc 进行连接。

我该怎么做?

我正在使用 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 var 来捕获数据

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

标签: iosswiftmapkitmkannotationmkannotationview

解决方案


您可以使用从 didSelectAnnotationView 中选择的注释,然后将该注释存储到实例变量中,然后在您的 prepare(for segue: method.

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
        }
    }

推荐阅读