MKAnnotation not getting selected in iOS5

2020-02-07 02:53发布

问题:

My app places a pushpin on the map and then selects its using animation so the user has a visual clue and can immediately read the title/subtitle. The following code works in both iOS4 and iOS5, but in iOS5, the annotation doesn't get selected automatically unless I change the animation to NO in the selectAnnotation method.

Any ideas why?

MapAnnotations *pushpin = [[MapAnnotations alloc] initWithCoordinate:coordinate];
pushpin.title = [selectedStation valueForKey:@"name"];
pushpin.subtitle = [selectedStation valueForKey:@"address"];
[stationMap addAnnotation:pushpin];
[stationMap selectAnnotation:pushpin animated:YES];

[pushpin release]; pushpin = nil;

回答1:

Not sure why it would work before but the animation probably requires the annotation view to be created and ready which is unlikely immediately after adding the annotation.

What you can do is move the selection to the didAddAnnotationViews delegate method which should work on all iOS versions:

- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
    for (MKAnnotationView *av in views) {
        if ([av.annotation isKindOfClass:[MapAnnotations class]]) {
            MapAnnotations *pushpin = (MapAnnotations *)av.annotation;
            if (_this_pushpin_is_the_one_to_select) {
                [mapView selectAnnotation:av.annotation animated:YES];
                break;  //or return;
            }
        }
    }
}