【发布时间】:2013-05-10 22:48:36
【问题描述】:
我正在做一个小项目,在地图上显示 7 种不同类型的注释。我的注释取自数组中的 url 结果,我使用 JSON 对其进行解析。我有很多注释,一旦地图加载,一切看起来都很好。放大和缩小后,pin 图像由于某种原因变为错误的 pin 图像(特定图像,不知道为什么)。
我确定我在这里遗漏了一些东西...请您帮忙 :) 吗?
这是我的代码的一部分,如果您需要,请告诉我:
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
static NSString *identifier;
if(_mapView.tag==1){identifier = @"TurbulencePin";}
if(_mapView.tag==2){identifier = @"IcingPin";}
if(_mapView.tag==3){identifier = @"WindsPin";}
if(_mapView.tag==4){identifier = @"TemperaturePin";}
if(_mapView.tag==5){identifier = @"CloudsPin";}
if(_mapView.tag==6){identifier = @"VisibilityPin";}
if(_mapView.tag==7){identifier = @"MultiplePin";}
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
if ([annotation isKindOfClass:[Annotation class]]) {
CustomAnnotationView* annotationView = (CustomAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
annotationView = nil;
if (annotationView == nil) {
annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
annotationView.enabled = YES;
annotationView.canShowCallout = YES;
UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:@"%@.png",identifier]];
annotationView.image = img;
}
else
{
annotationView.annotation = annotation;
}
return annotationView;
}
return nil;
}
更新:
根据其他人的反馈,我将图片设置的代码修改如下:
Annotation *myCustomAnn = (Annotation *)annotation;
NSString *imgName = myCustomAnn.imageName;
UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:@"%@Pin.png",imgName]];
annotationView.image = img;
return annotationView;
另外,我删除了annotationView = nil;
但是,我无法将 annotation.m 中的图像名称设置为硬编码值,因为我需要为每个注释显示不同的 pin 图像。我确定有一个解释,但我可以从 mapView:viewForAnnotation: 下的 annotation.m 获得的唯一值是注释坐标(myCustomAnn.coordinate.latitude 和 myCustomAnn.coordinate.longitude),我不知道如何获取其他属性来自注解.m
其他属性,如title、imgname等返回为null
【问题讨论】:
-
这个注解类型应该是注解的一个属性,而不是使用地图的
tag属性。 (顺便说一句,如果您以编程方式设置它,您的identifier不需要是静态的。)但我能想象的唯一会导致图钉图像发生变化的是tag是否以某种方式发生变化。我建议记录一下,看看发生了什么(但更好的是,放弃tag并为您的注释使用自定义属性)。 -
顺便说一句,我希望你不要同时打开七张地图。如果你这样做了,不要使用
_mapView(这是一些ivar),而是使用mapView,这个方法的参数。 -
您说“无法在 annotation.m 中设置图像名称 ...”。正确的。你不应该在 annotation.m 中这样做。在您的 annotation.h 中,您应该简单地为
imageName定义一个新属性。然后在创建注释后创建注释的代码(您的视图控制器?)中,您可以在其中为注释设置imageName属性。关于您的其他属性为空,问题是您是否在您的 VC 中设置了这些属性,您在其中执行了注释对象的alloc/init,但在您执行addAnnotation调用之前。 -
我通过使用 JSON 解析许多注释的数组来提供注释属性。该数组包括每个注释的坐标、标题等。所以基本上,坐标和其余属性是同时设置的,我可以从 annotation.m 传递到 mapView:viewForAnnotation: 的唯一属性是坐标... :/ 我错过了什么和 Rob ,对于你的问题,不,我只使用一张地图
-
在为该注记设置所有属性之前,您不应将该注记添加到您的地图中。
addAnnotation应该是最后一步。或者,有时我会将注释添加到NSMutableArray,将它们调整到我心中的内容,然后,最后,我将使用addAnnotations(注意s),将它传递给我的数组.
标签: ios mapkit mkannotationview