mapView calloutAccessoryControlTapped,如何知道谁发布了它?

时间:2016-02-08 22:53:57

标签: swift mkmapview mapkit mkannotation mkannotationview

我正在处理一个带有地图的项目,有一些注释的视图有一个详细信息按钮。

这些注释是在for循环中创建的,我以JSON格式获取数据,并为每个元素创建注释。 但是,Annotations(或AnnotationViews)与这些元素之间没有直接的关联。

...
anView?.rightCalloutAccessoryView = UIButton(type: .DetailDisclosure)
...

func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
        self.performSegueWithIdentifier("openInfo", sender: control)
    }

我知道这个按钮使用calloutAccessoryControlTapped调用mapView函数,并传递AnnotationView。

问题在于,即使我知道调用segue的AnnotationView,我也不知道它的响应是什么。 有没有办法在AnnotationView中保存一些信息?我的意思是,所以AnnotationView的每个实例都有一个可以与我收到的数据相关的ID?

还有其他想法吗?

由于

1 个答案:

答案 0 :(得分:1)

您可以从以下位置访问所选注释:

let selectedAnnotation = view.annotation as! CustomAnnotation // See structure below.

如果您有要访问的数据源,建议您为MKAnnotation创建一个包含对数据源的引用的自定义对象,如标识符。然后设置:

selectedId = selectedAnnotation.id
performSegueWithIdentifier("openInfo", sender: control)

并在prepareForSegueselectedId传递给接收视图控制器。

编辑:您的注释类看起来像这样:

class CustomAnnotation: NSObject, MKAnnotation {
    var title: String?
    var coordinate: CLLocationCoordinate2D
    var subtitle: String?

    var id: Int

    init(title: String, coordinate: CLLocationCoordinate2D, subtitle: String, id: Int) {
        self.title = title
        self.coordinate = coordinate
        self.subtitle = subtitle

        self.id = id
    }
}