0

我在 Apple 的Location and Maps Programming Guide中看到了这段代码:

- (MKAnnotationView *)mapView:(MKMapView *)mapView
                      viewForAnnotation:(id <MKAnnotation>)annotation
{
    // If the annotation is the user location, just return nil.
    if ([annotation isKindOfClass:[MKUserLocation class]])
        return nil;

    // Handle any custom annotations.
    if ([annotation isKindOfClass:[MyCustomAnnotation class]])
    {
        // Try to dequeue an existing pin view first.
        MKPinAnnotationView*    pinView = (MKPinAnnotationView*)[mapView
        dequeueReusableAnnotationViewWithIdentifier:@"CustomPinAnnotationView"];

        if (!pinView)
        {
            // If an existing pin view was not available, create one.
            pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation
                       reuseIdentifier:@"CustomPinAnnotationView"];
            pinView.pinColor = MKPinAnnotationColorRed;
            pinView.animatesDrop = YES;
            pinView.canShowCallout = YES;

            // If appropriate, customize the callout by adding accessory views (code not shown).
        }
        else
            pinView.annotation = annotation;

        return pinView;
    }

    return nil;
}

我有一个关于这部分的问题:

else
    pinView.annotation = annotation;

我在 Stackoverflow答案中看到了相同的代码:

不相关,但您还需要annotation在重新使用视图时设置视图的属性(在出队后不为 nil 的情况下)。所以添加一个else块到if (pinAnnotation == nil)

else {
    //annotation view being re-used, set annotation to current...
    pinAnnotation.annotation = annotation;
}

为什么在 else 块中设置了注解属性?无论视图是否被重用,不应该设置注释吗?

4

1 回答 1

0

您使用注释初始化,MKPinAnnotationView所以 else 只是这样您就不会设置它两次。设置两次完全没问题,但当然效率低下。

于 2016-02-10T15:25:53.430 回答