放大/缩小时MKAnnotationView错误更改了图钉图像

我使用了注释图并为引脚使用了多个图像,但每当我放大或缩小时,它都会将所有引脚更改为一个图像。

我从Web服务获取位置并识别它们,我使用字符串( CustAttr )作为“T”或“P”。

问题是来自Web服务的最后一次调用使CustAttr = T ,当我放大或缩小时,它调用mapView viewForAnnotation方法并将它们全部绘制为T并且所有P引脚都被更改。

以下是该方法的代码:

 -(MKAnnotationView*) mapView:(MKMapView *)mapView viewForAnnotation:(id)annotation { if ([annotation isKindOfClass:[MKUserLocation class]]) { return nil; } static NSString* AnnotationIndentifer = @"AnnotationIdentifier"; if ([custAttr isEqualToString:@"T"]) // ATMs { MKAnnotationView* pinView; pinView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIndentifer]; MapAnnotation* mapAnnotation = annotation; pinView.canShowCallout = YES; UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeInfoLight]; pinView.rightCalloutAccessoryView = rightButton; if (mapAnnotation.isClosest) { pinView.image = [UIImage imageNamed:@"Closest_ATM.png"]; } if (mapAnnotation.isOffline) { pinView.image = [UIImage imageNamed:@"Offline_ATM.png"]; } pinView.annotation = annotation; return pinView; }else if ([custAttr isEqualToString:@"P"]) // POIs { MKAnnotationView* pinView; pinView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIndentifer]; pinView.canShowCallout = YES; pinView.image = [UIImage imageNamed:@"Location_POI.png"]; pinView.annotation = annotation; return pinView; } return nil; } 

我该如何解决这个问题? 是否有一种方法可以阻止它在放大/缩小时调用此方法,或者是否有另一种方法让它在同一图像中再次绘制它们?

custAttr变量(您在委托方法之外设置)并不总是与viewForAnnotation委托方法的annotation同步。

如果地图需要在缩放或平移后再次显示注释视图,则不必在addAnnotationaddAnnotations之后addAnnotation调用委托方法,并且可以为每个注释多次调用委托方法。

当再次调用相同的注释时, custAttr变量不再匹配。

您需要向MapAnnotation类添加custAttr属性(我建议使用不同的名称),并在创建注释时设置它(在调用addAnnotation之前)。

例如:

 MapAnnotation *ann = [[MapAnnotation alloc] init]; ann.coordinate = ... ann.title = ... ann.subtitle = ... ann.custAttr = custAttr; // <-- copy to the annotation object itself [mapView addAnnotation:ann]; 

然后,在viewForAnnotation ,从annotation参数中读取custAttr属性(在将其转换为MapAnnotation * ),而不是引用外部声明的custAttr

您可能希望在MapAnnotationcustAttr属性使用其他名称以避免混淆。