Map view annotations with different pin colors

送分小仙女□ 提交于 2019-11-27 05:29:10

The viewForAnnotation delegate method isn't necessarily called immediately after you do addAnnotation and it can also be called at other times by the map view when it needs to get the view for an annotation (while your code is doing something completely different).

So you can't depend on the value of an ivar being in sync with some code outside that delegate method.

Instead, add the yesno property to your custom MapViewAnnotation class, set it when creating the annotation and then access its value in viewForAnnotation through the annotation parameter (ie. the map view is giving you a reference to the exact annotation object it wants the view for).

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;
}
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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!