我正在开发一个带有 map 的项目,有一些注释的 View 有一个详细信息按钮。
这些注释是在 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,我也不知道this响应的是谁。 有什么办法可以在AnnotationView中保存一些信息吗?我的意思是,这样 AnnotationView 的每个实例都有一个可以与我收到的数据相关的 ID?
还有其他想法吗?
谢谢
最佳答案
您可以从以下位置访问选定的注释:
let selectedAnnotation = view.annotation as! CustomAnnotation // See structure below.
如果您有要访问的数据源,建议为您的 MKAnnotation
创建一个自定义对象,其中包含对数据源的一些引用,例如标识符。然后设置:
selectedId = selectedAnnotation.id
performSegueWithIdentifier("openInfo", sender: control)
并在您的 prepareForSegue
中将 selectedId
传递给接收 View Controller 。
编辑:您的注释类可能如下所示:
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
}
}
关于swift - mapView calloutAccessoryControlTapped,如何知道是谁发起的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35280918/