多个注释arrays,每个arrays的引脚颜色不同?

我的应用程序中有三个注释数组,foodannotations,gasannotations和shoppingnotnotations。 我希望每个注释数组都显示不同颜色的引脚。 我目前正在使用

- (MKAnnotationView *)mapView:(MKMapView *)sheratonmap viewForAnnotation:(id)annotation { NSLog(@"Welcome to the Map View Annotation"); if([annotation isKindOfClass:[MKUserLocation class]]) return nil; static NSString* AnnotationIdentifier = @"Annotation Identifier"; MKPinAnnotationView* pinview = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] autorelease]; pinview.animatesDrop=YES; pinview.canShowCallout=YES; pinview.pinColor=MKPinAnnotationColorPurple; UIButton* rightbutton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; [rightbutton setTitle:annotation.title forState:UIControlStateNormal]; [rightbutton addTarget:self action:@selector(showDetails) forControlEvents:UIControlEventTouchUpInside]; pinview.rightCalloutAccessoryView = rightbutton; return pinview; } 

如何将其设置为为每个注释数组使用三种不同的引脚颜色。

谢谢!

您是否定义了一个实现MKAnnotation协议的自定义类,您在其中添加了一些标识它是什么类型的注释的属性? 或者您是否为实现MKAnnotation定义了三个单独的类(每种类型的注释一个)?

假设您已经定义了一个注释类,其中您的注释类中有一个名为annotationTypeint属性,那么您可以在viewForAnnotation执行此操作:

 int annType = ((YourAnnotationClass *)annotation).annotationType; switch (annType) { case 0 : //Food pinview.pinColor = MKPinAnnotationColorRed; case 1 : //Gas pinview.pinColor = MKPinAnnotationColorGreen; default : //default or Shopping pinview.pinColor = MKPinAnnotationColorPurple; } 

其他几件事:

  • 您应该使用dequeueReusableAnnotationViewWithIdentifier:方法
  • 不使用addTarget:action和自定义方法来处理callout按钮,而是使用map视图的委托方法calloutAccessoryControlTapped 。 在该委托方法中,您可以使用view.annotation访问注释。

我建议你创建一个自定义MKAnnotation并有一个自定义属性(最可能是一个typedef枚举)来区分不同类型的注释。

 typedef enum { Food, Gas, Shopping } AnnotationType 

之后, if (annotation.annotationType == Food) { set pinColor } ,您可以有条件地设置颜色

当然,您可以使用AnnotationType的switch语句来获得更清晰的代码:

 switch(annotation.annotationType) { case Food: do something; break; case Gas: do something; break; case Shopping: do something; break; } 

有关添加更多颜色的更多信息,请参阅以下问题(如果您希望稍后扩展您的应用):

MKPinAnnotationView:有三种以上的颜色吗?


这是一个教程中的代码片段,显示了大量的修改:

 calloutMapAnnotationView.contentHeight = 78.0f; UIImage *asynchronyLogo = [UIImage imageNamed:@"asynchrony-logo-small.png"]; UIImageView *asynchronyLogoView = [[[UIImageView alloc] initWithImage:asynchronyLogo] autorelease]; asynchronyLogoView.frame = CGRectMake(5, 2, asynchronyLogoView.frame.size.width, asynchronyLogoView.frame.size.height); [calloutMapAnnotationView.contentView addSubview:asynchronyLogoView]; 

HTH