How to keep data associated with MKAnnotation from being lost after a callout pops up and user taps disclosure button?

前提是你 提交于 2019-11-26 21:07:16

In the showPinDetails: method, you can get the currently selected annotation from the map view's selectedAnnotations property.

That property is an NSArray but since the map view only allows one annotation to be selected at a time, you would just use the object at index 0. For example:

- (void)showPinDetails:(id)sender
{
    if (mapView.selectedAnnotations.count == 0)
    {
        //no annotation is currently selected
        return;
    }

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

    if ([selectedAnn isKindOfClass[VoiceMemoryAnnotation class]])
    {
        VoiceMemoryAnnotation *vma = (VoiceMemoryAnnotation *)selectedAnn;
        NSLog(@"selected VMA = %@, blobkey=%@", vma, vma.blobkey);
    }
    else
    {
        NSLog(@"selected annotation (not a VMA) = %@", selectedAnn);
    }

    detailViewController = [[MemoryDetailViewController alloc]initWithNibName:@"MemoryDetailViewController" bundle:nil];
    [self presentModalViewController:detailViewController animated:YES];
}


Instead of using a custom button action method, it can be easier to use the map view's calloutAccessoryControlTapped delegate method which lets you get access to the selected annotation more directly. In viewForAnnotation, remove the addTarget and just implement the delegate method:

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view 
    calloutAccessoryControlTapped:(UIControl *)control
{
    id<MKAnnotation> selectedAnn = view.annotation;

    if ([selectedAnn isKindOfClass[VoiceMemoryAnnotation class]])
    {
        VoiceMemoryAnnotation *vma = (VoiceMemoryAnnotation *)selectedAnn;
        NSLog(@"selected VMA = %@, blobkey=%@", vma, vma.blobkey);
    }
    else
    {
        NSLog(@"selected annotation (not a VMA) = %@", selectedAnn);
    }

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