我有一个包含 200 多个对象的数组,我试图对每个对象执行循环。
每个对象都有一个是/否字段,我想根据该是/否值显示不同颜色的标记。
从我所看到的情况来看,我的循环首先遍历每个对象,然后在每个对象的末尾添加所有注释。
由于当所有注释都添加到我的地图时,我在循环中通过数组执行是/否值检查,因此当它为所有注释绘制时,它将使用数组中最后一个对象的是/否值。
我怎样才能拥有它,以便标记会根据每个单独元素的是/否值而有所不同?
我的代码是
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;
}
and current_yesno
在我的 .h 文件中声明。
The viewForAnnotation
委托方法不一定在执行后立即调用addAnnotation
当地图视图需要获取注释视图时(当您的代码正在执行完全不同的操作时),它也可以在其他时候由地图视图调用。
因此,您不能依赖 ivar 的值与该委托方法之外的某些代码同步。
相反,添加yesno
您定制的财产MapViewAnnotation
类,在创建注释时设置它,然后访问它的值viewForAnnotation
通过annotation
参数(即地图视图为您提供对其想要视图的确切注释对象的引用)。
Example:
MapViewAnnotation *newAnnotation = [[MapViewAnnotation alloc] init...
newAnnotation.yesno = tempObj.yesno; // <-- set property in annotation
[self.mapView addAnnotation:newAnnotation];
Then in 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)