2
votes

I have a MKMapView annotation object that has a right callout accessory detail disclosure button. When the button is pressed I am using addTarget:action:forControlEvent to call a selector method which creates a detail viewController and pushes it onto the view stack.

My question is what is the best way to access the information on the annotation that initiated the callout detail controller. The detail disclosure button is set to call:

[button addTarget:self action:@selector(disclosurePressed:) forControlEvents:UIControlEventTouchUpInside];

Which looks like this:

- (void)disclosurePressed:(id)sender {
}

I guess I could look for the parent annotation of the sender UIButton, can anyone give me any pointers to how this is best done.

2

2 Answers

4
votes

You might have an easier time using the MKMapViewDelegate mapView:annotationView:calloutAccessoryControlTapped: method, which tells you directly which annotation view was tapped.

3
votes

A reliable way (if you must use a custom method) is to look at the map view's selectedAnnotations property.

Though the property is an NSArray, since the map view only allows one annotation to be selected at a time, the one that the user just tapped will be at index 0 so it would be:

id<MKAnnotation> annTapped = [mapView.selectedAnnotations objectAtIndex:0];

//Here, you can cast annTapped to a custom annotation class if needed.
//Be sure to check what kind of class it is first.

You may also want to first check that mapView.selectedAnnotations.count is not zero just to be safe.


However, a better way (as nevan king already answered) than using addTarget and a custom action method is to use the map view's calloutAccessoryControlTapped delegate method where the annotation is directly accessible through the view parameter using:

id<MKAnnotation> annTapped = view.annotation;