2

这是我的代码:

- (MKAnnotationView *)mapView:(MKMapView *)aMapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    if ([annotation class] == MKUserLocation.class) {
        return nil;
    }
    static NSString *identifier=@"an";

    MKAnnotationView *pinView = nil;

    pinView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];

    if (pinView == nil)
    {
        pinView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
        pinView.canShowCallout = YES;
        NSLog(@"NEW ONE CREATED");
    }
    else
    {
        pinView.annotation = annotation;
    }

    return pinView;
} 

似乎这不起作用,并且 pinView 始终为零,因为我可以看到创建的每个 pin 的 nslog。

4

1 回答 1

2

Two thoughts:

  1. Don't assume that just because an annotation has scrolled off the current map view's current region, that it is automatically available for being dequeued and reused for another annotation immediately. It's quite possible that MKMapView is going to hang onto annotation views, not making them available for reuse immediately. For example, I could imagine some internal optimization that might hang on to annotation views that are near the map's current region in case that the user scrolls their map such that that previous annotation view is now visible again. MKMapView probably wants to avoid creating and recreating the same annotation view as the user scrolls the MKMapView back and forth.

    In my experience, you have to scroll some distance before the old annotation views are made available for reuse.

  2. This is extremely unlikely, but in addition to my observation above, we should note that your viewForAnnotation references some external variable, mapView, rather than using the aMapView that was passed as a parameter to the method. Most likely this is some instance variable that is pointing to the same MKMapView, and everything is fine, but if that mapView variable is nil, the dequeueReusableAnnotationViewWithIdentifier will always return nil, too. You might want to change your viewForAnnotation to use the aMapView parameter to remove this ambiguity.

于 2013-07-15T00:12:37.137 回答