Map view annotations with different pin colors

后端 未结 2 526
无人共我
无人共我 2020-11-30 14:32

I have an array with over 200 objects and I am trying to perform a loop through each of them.

Each object will have a yes/no field and I want to display a different

相关标签:
2条回答
  • 2020-11-30 14:43

    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;
    }
    
    0 讨论(0)
  • 2020-11-30 15:06
    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;
    
    0 讨论(0)
提交回复
热议问题