FrCr February 2016

mapView calloutAccessoryControlTapped, how to know who launched it?

I'm working on a project with a map, there are some annotations whose views have a detail button.

Those annotations are created in a for loop where I get data in JSON format, and for every element an annotation is created. However there's no direct correlation between Annotations (or AnnotationViews) and those elements.

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

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

I understand that this button calls the mapView function with calloutAccessoryControlTapped, and passes the AnnotationView.

The problem is that, even if I know the AnnotationView that called the segue, I don't know whose this responds to. Is there any way to save some informations in the AnnotationView? I mean, so that every instance of AnnotationView has an ID that can relate to the data i received?

Any other idea?

Thanks

Answers


dzk February 2016

You can access the selected annotation from:

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

And if you have a data source which you want to access, it's recommended to create a custom object for your MKAnnotations that contain some reference to your data source, like an identifier. And then set:

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

And in your prepareForSegue pass the selectedId to the receiving view controller.

EDIT: Your annotation class could look something like this:

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

Post Status

Asked in February 2016
Viewed 1,954 times
Voted 4
Answered 1 times

Search




Leave an answer