How to recognize which pin was tapped

醉酒当歌 提交于 2019-11-26 04:51:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!