用不同的针脚颜色映射视图注释
我有一个超过200个对象的数组,我试图执行每个循环。
每个对象将有一个是/否的字段,我想显示一个不同的颜色标记依赖是/否的值。
从我所看到的是我的循环正在经历每个对象,然后在每个对象的末尾添加所有的注释。
由于我在循环中通过数组中的yes no值执行了一个检查,当所有的注释被添加到我的地图中时,它将使用来自数组中最后一个对象的yes / no值。
我怎么能这样做,这样标记将是不同的取决于每个元素的是/否值?
我的代码是
for (i = 0; i < [appDelegate.itemArray count]; i++) { item_details *tempObj = [appDelegate.itemArray objectAtIndex:i]; location.latitude = [tempObj.lat floatValue]; location.longitude = [tempObj.lon floatValue]; current_yesno = tempObj.yesno; MapViewAnnotation *newAnnotation = [[MapViewAnnotation alloc]initWithTitle:tempObj.name andCoordinate:location]; [self.mapView addAnnotation:newAnnotation]; [newAnnotation release]; }
我的注释代码如下
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{ MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"]; if(current_yesno == YES){ annView.pinColor = MKPinAnnotationColorGreen; } else { annView.pinColor = MKPinAnnotationColorRed; } annView.animatesDrop=NO; annView.canShowCallout = YES; annView.calloutOffset = CGPointMake(-5, 5); return annView; }
而current_yesno
是在我的.h文件中声明的。
viewForAnnotation
委托方法不一定会在你执行addAnnotation
之后立即被调用,而且当需要获得注解的视图(而你的代码做了完全不同的事情)的时候,也可以在地图视图中viewForAnnotation
委托方法。
所以你不能依靠一个ivar与代理方法外部的一些代码同步的价值。
相反,将yesno
属性添加到您的自定义MapViewAnnotation
类中,在创build注释时对其进行设置,然后通过annotation
参数在viewForAnnotation
访问其值(即地图视图为您提供了对要查看的确切注释对象的引用)。
例:
MapViewAnnotation *newAnnotation = [[MapViewAnnotation alloc] init... newAnnotation.yesno = tempObj.yesno; // <-- set property in annotation [self.mapView addAnnotation:newAnnotation];
然后在viewForAnnotation
:
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation { if (![annotation isKindOfClass:[MapViewAnnotation class]]) { // Return nil (default view) if annotation is // anything but your custom class. return nil; } static NSString *reuseId = @"currentloc"; MKPinAnnotationView *annView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseId]; if (annView == nil) { annView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId]; annView.animatesDrop = NO; annView.canShowCallout = YES; annView.calloutOffset = CGPointMake(-5, 5); } else { annView.annotation = annotation; } MapViewAnnotation *mvAnn = (MapViewAnnotation *)annotation; if (mvAnn.yesno) { annView.pinColor = MKPinAnnotationColorGreen; } else { annView.pinColor = MKPinAnnotationColorRed; } return annView; }
MKPinAnnotationView *pin = (MKPinAnnotationView *) [self.mapView dequeueReusableAnnotationViewWithIdentifier: @"id"]; if (pin == nil) { pin = [[MKPinAnnotationView alloc] initWithAnnotation: annotation reuseIdentifier: @"id"] ; } else { pin.annotation = annotation; } pin.pinTintColor=[UIColor blueColor]; pin.canShowCallout = true;