我有NSArray
自定义MKAnnotation
,我需要为第一个/最后一个注释设置一个红色引脚颜色,否则设置一个绿色引脚。
程序没有按照我想要的方式运行,绿色引脚每次都以随机的方式与两个不同的注释相关联,并不像我想要的那样与第一个和最后一个相关联。
所以,这就是我在我的控制器中所做的事情:
- (void)viewDidLoad
{
[super viewDidLoad];
//load set a coords from file etc...
//self.coordinates is the array of annotations
[self.myMap addAnnotations:self.coordinates];
}
然后在viewForAnnotation中:回调:
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
NSString *ident = @"MY_IDENTIFIER";
MKPinAnnotationView *annView=(MKPinAnnotationView *)[self.myMap dequeueReusableAnnotationViewWithIdentifier:ident];
if(self.myMap.userLocation==annotation){
return nil;
}
if(annView == nil){
annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:ident];
annView.animatesDrop=TRUE;
annView.canShowCallout = YES;
annView.rightCalloutAccessoryView=[UIButton buttonWithType:UIButtonTypeDetailDisclosure];
annView.calloutOffset = CGPointMake(-5, 5);
int currIdxAnn=[self.myMap.annotations indexOfObject:annotation];
int lastIdxAnn=[self.myMap.annotations indexOfObject:[self.myMap.annotations lastObject]];
/*
if (currIdxAnn==0 || currIdxAnn==lastIdxAnn) {
annView.pinColor=MKPinAnnotationColorRed;
}else {
annView.pinColor=MKPinAnnotationColorGreen;
}*/
CustomAnnotation *an=(CustomAnnotation *)annotation;
if (an.tag==98||an.tag==99) {
annView.pinColor=MKPinAnnotationColorGreen;
}else {
annView.pinColor=MKPinAnnotationColorRed;
}
}
return annView;
}
似乎方法addAnnotations:
无法正常工作,可能会加载带有与数组不同的顺序的注释。有可能吗?
我还尝试在didAddAnnotationViews:
中进行类似的处理,但没有取得好成绩。
一些提示? 感谢。
PS:当我写完这个问题时,我发现了this回复,似乎证实了我的理论。有人已经遇到过类似的问题吗?
编辑:经过多次测试后,我意识到实现我想要的最好方法是首先为我的第一个/最后一个注释设置标签:
CustomAnnotation *first=[self.coordinates objectAtIndex:0];
first.tag=98;
CustomAnnotation *last=[self.coordinates objectAtIndex:[self.coordinates indexOfObject:[self.coordinates lastObject]]];
last.tag=99;
然后你可以看到我稍微修改了viewForAnnotation
以理解注释是我寻找的那个。
然后技巧就是调用在后台线程中添加注释的函数,如:
[self performSelectorInBackground:@selector(addAllAnnot) withObject:nil];
-(void)addAllAnnot{
[self.myMap addAnnotations:self.coordinates];
}
经过一周的测试后,这对我有用,如果有人有更好的想法,我们将不胜感激。
答案 0 :(得分:2)
查看您在答案中提到的答案我认为您无法确定添加这些注释的顺序或它们在mapview的内部列表中具有的索引。
那么你有什么选择..?一如既往地非常基础 - 对MKAnnotation类进行子类化并为其添加属性,通过该属性可以区分添加的注释。因此,只需在数组中添加这些注释时设置属性...希望这可以解决您的问题..
答案 1 :(得分:0)
我不会指望地图给出的阵列。它可能是由mapkit以一种对您来说不明显的方式进行优化的。
我会从您计算的坐标中保留一个变量。或者如果你不想要,只需要一个第一个和最后一个注释的数组。