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

后端 未结 1 828
北荒
北荒 2020-11-27 23:21

How do I keep data associated with an MKAnnotation object after the user taps the pin, sees a callout, and taps the disclosure button which opens a detailed view controller?

相关标签:
1条回答
  • 2020-11-27 23:48

    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... 
    }
    
    0 讨论(0)
提交回复
热议问题