用不同的针颜色映射视图注释

use*_*447 5 annotations objective-c mapkit ios

我有一个包含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];            
            } 
Run Code Online (Sandbox Code Playgroud)

我的注释代码如下

- (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;

}
Run Code Online (Sandbox Code Playgroud)

current_yesno在我的.h文件中声明.

小智 8

viewForAnnotation委托方法你以后不一定马上叫addAnnotation,它也可以在通过地图查看其他时间时,它需要获得注释的视图(而你的代码做一些完全不同的)被调用.

因此,您不能依赖于ivar与该委托方法之外的某些代码同步的值.

相反,将yesno属性添加到自定义MapViewAnnotation类,在创建注释时设置它,然后viewForAnnotation通过annotation参数访问其值(即,地图视图为您提供了对其所需视图的确切注释对象的引用).

例:

MapViewAnnotation *newAnnotation = [[MapViewAnnotation alloc] init...
newAnnotation.yesno = tempObj.yesno;  // <-- set property in annotation
[self.mapView addAnnotation:newAnnotation];
Run Code Online (Sandbox Code Playgroud)

然后在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;
}
Run Code Online (Sandbox Code Playgroud)