Search code examples
iosobjective-cmkmapviewmkannotationview

didDeselectAnnotationView not called when tap on map view


I've build a map view controller and everything works fine. When selecting an annotation view on the map, a custom view will be showed on the screen to display some information about that annotation. Tap on the map will deselect that annotation view and hide the custom view.

I get a requirement now, that if there is only one annotation on the view, show the custom view when the map view controller is pushed in. So I simply implement

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view

when map view finished loading.

- (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView {
    if (self.viewModel.pointsArray.count == 1) {
        GSMapsLocationPoint* point = self.viewModel.pointsArray.lastObject;
        MKAnnotationView *annotationView = [self.mapsView viewForAnnotation:point];
        [self mapView:self.mapsView didSelectAnnotationView:annotationView];
    }
}

However, when I tap on the map, - (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view will not get called. If I tap on that annotation view manually, then didSelectAnnotationView will get called correctly.

It seems like that call didSelectAnnotationView in code will not change some status so that map view doesn't know there is a annotation view is selected.

How can I fix this? Thanks in advance.


Solution

  • You should use selectAnnotation: instead of didSelectAnnotationView:, try replacing this:

    [self mapView:self.mapsView didSelectAnnotationView:annotationView];
    

    with this:

    [self.mapsView selectAnnotation:point animated:YES];
    

    didSelectAnnotationView: will be called by your mapView when the annotation is selected.