I've an 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 https://stackoverflow.com/a/9543136/251513回应,似乎证实了我的理论。有人已经遇到过类似的问题吗?
EDIT:经过几次测试,我意识到实现我想要的最好方法是首先为我的第一个/最后一个注释设置一个标签:
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];
}
经过一周的测试后,这对我有用,如果有人有更好的想法,我们将不胜感激。