问题
I got an app with MKMapView
and large number of pins on this map.
Every pin got rightCalloutAccessoryView
. I create it in this way:
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton addTarget:self action:@selector(showDetails:) forControlEvents:UIControlEventTouchUpInside];
pinView.rightCalloutAccessoryView = rightButton;
How should i know, which pin was tapped? Thnx
回答1:
In the showDetails:
method, you can get the pin tapped from the map view's selectedAnnotations
array. Even though the property is an NSArray
, just get the first item in the array since the map view only allows one pin to be selected at a time:
//To be safe, may want to check that array has at least one item first.
id<MKAnnotation> ann = [[mapView selectedAnnotations] objectAtIndex:0];
// OR if you have custom annotation class with other properties...
// (in this case may also want to check class of object first)
YourAnnotationClass *ann = [[mapView selectedAnnotations] objectAtIndex:0];
NSLog(@"ann.title = %@", ann.title);
By the way, instead of doing addTarget
and implementing a custom method, you can use the map view's calloutAccessoryControlTapped
delegate method. The annotation tapped is available in the view
parameter:
-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view
calloutAccessoryControlTapped:(UIControl *)control
{
NSLog(@"ann.title = %@", view.annotation.title);
}
Make sure you remove the addTarget
from viewForAnnotation
if you use calloutAccessoryControlTapped
.
来源:https://stackoverflow.com/questions/9462699/how-to-recognize-which-pin-was-tapped