edit:: There's a much better solution using key-value observing, which includes adding an observer to the selected
property of the MKAnnotationView
, then dealing with it appropriately in the callback:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
You can view the solution here: http://blog.evandavey.com/2009/07/how-to-detect-when-mkannotation-mkannotationview-is-selected.html
(old solution)
I had a similar problem. It looks like you've gotten most of it. In your function:
- (MKAnnotationView *)mapView:(MKMapView *)aMapView
viewForAnnotation:(id <MKAnnotation>)annotation
Just make sure to add a callback (aka. selector) to each annotation. For me, I actually want a UIButton
for them to click on, so I created one and added it as the rightCalloutAccessoryView
for the annotation.
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton addTarget:self
action:@selector(showDetails:)
forControlEvents:UIControlEventTouchUpInside];
customPinView.rightCalloutAccessoryView = rightButton;
I then created a function called showDetails
in whatever delegate you passed to the addTarget
variable (in my case self, which is a custom UIViewController
).
Now, whenever anyone clicks on any annotation, the showDetails
function gets called.
However, I'm having problems with figuring out which specific annotation gets called, as I have many on my map, and the caller of the showDetails
function is not the annotation, but the specific UIButton
.
I've looked into this solution: http://stackoverflow.com/questions/2329654/clean-solution-to-know-which-mkannotation-has-been-tapped, but it only deals with the event inside viewForAnnotation
, which, as you mentioned, only gets called at the creation of each annotation, and not when they get tapped.