20
votes

I have a MKMapView that has a number of annotations. Selecting the pin displays the callout and pressing the accessory pops a new viewcontroller onto the stack. However when I press back from that new VC the callout is still open. How do I close it?

I have tried

if([[myMapView selectedAnnotations] count] > 0)
{
    //deselect that annotation
    [myMapView deselectAnnotation:[[myMapView selectedAnnotations] objectAtIndex:0] animated:NO];
}

but this does not work. The selectedAnnotations does have a single entry in the array so it does go into this statement but the callout is not closed.

Do I need to add something to my MKAnnotation implementation or my MKPinAnnotationView?

7

7 Answers

41
votes

The objects in selectedAnnotations are instances of MKAnnotation

NSArray *selectedAnnotations = mapView.selectedAnnotations;
for(id annotation in selectedAnnotations) {
    [mapView deselectAnnotation:annotation animated:NO];
}
13
votes

In case you want to stick with the map kit documentation.

for (NSObject<MKAnnotation> *annotation in [mapView selectedAnnotations]) {
    [mapView deselectAnnotation:(id <MKAnnotation>)annotation animated:NO];
}
4
votes

Swift

Close (deselect) all annotations programmatically...

mapView.selectedAnnotations.forEach({ mapView.deselectAnnotation($0, animated: false) })
3
votes
func mapView(mapView: MKMapView, annotationView view: MKAnnotationView,
             calloutAccessoryControlTapped control: UIControl)
{
    let pin = view.annotation
    mapView.deselectAnnotation(pin, animated: false)
    performSegueWithIdentifier("Next VC Segue", sender: nil)
}

Deselect the annotation just before you segue to the new view controller. That way it will be gone when you return.

1
votes

In lieu of a nice solution the following hacky approach works in the viewWillAppear:animated

    for( MyMapAnnotation *aMKAnn in  [myMapView annotations])
    {
        //dodgy select then deselect each annotation
        [myMapView selectAnnotation:aMKAnn animated:NO];
        [myMapView deselectAnnotation:aMKAnn animated:NO];
    }

the selectedAnnotations array does have 1 value but deselecting that value still did not close the call out? So I simply iterate through all annotations and select and deselect. I don't have many annotations so probably not too bad a performance hit?

I would appreciate an elegant solution if anyone has better ideas?

0
votes

When you reclick the pin the callout should go away...

0
votes
- (void)deselectAllAnnotations
{

    NSArray *selectedAnnotations = [self.mapViewObj.mapView selectedAnnotations];
    for (int i = 0; i < [selectedAnnotations count]; i++) {
        [self.mapViewObj.mapView deselectAnnotation:[selectedAnnotations objectAtIndex:i] animated:NO];
    }

}

This may help you in solving your problem.