2
votes

I am trying to change colour of annotation pin on MKMapView by overriding this below:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
// If it's the user location, just return nil.
if ([annotation isKindOfClass:[MKUserLocation class]])
    return nil;

// Handle any custom annotations.
if ([annotation isKindOfClass:[MKPointAnnotation class]])
{
    MKPinAnnotationView *pinView = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:@"CustomPinAnnotationView"];
    if (!pinView)
    {
        pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"CustomPinAnnotationView"];
        pinView.canShowCallout = YES;
        pinView.pinColor = MKPinAnnotationColorGreen;
    } else {
        pinView.annotation = annotation;
    }
    return pinView;
}
return nil;
}

Here below are relevant methods:

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

[self configureView];
}


- (void)configureView
{
// Update the user interface for the detail item.
if (self.detailItem) {

    // display map ????
    PFGeoPoint *geoPoint = self.detailItem[@"location"];
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(geoPoint.latitude,geoPoint.longitude);

    MKPointAnnotation *annotation =[[MKPointAnnotation alloc] init];
    annotation.coordinate = coordinate;

    // remove previous annotation pin
    if([self.mapView.annotations count] == 1) {
        [self.mapView removeAnnotation:[self.mapView.annotations objectAtIndex:0]];
    }

    [self.mapView addAnnotation:annotation];
    annotation.title = self.detailItem[@"text"];

    MKCoordinateSpan span = {.latitudeDelta =  0.05, .longitudeDelta =  0.05};
    MKCoordinateRegion region = {coordinate, span};
    [self.mapView setRegion:region];

    [self.mapView setCenterCoordinate:self.mapView.region.center animated:NO];

}

}

My problem is pin annotation colour is still shown Red as default not Green as I want. What am I missing here?

1
Make sure the map view's delegate is set or connected.user467105
Hi @Anna could you tell me where to do this thing or even better show me some example please?SanitLee
If the map view is an IBOutlet, in the xib or storyboard, connect the map view's delegate outlet to the mapView property. Or in viewDidLoad, do self.mapView.delegate = self;. The code in viewForAnnotation looks fine but if the delegate is not set, the method won't get called.user467105
It appears that I missed this self.mapView.delegate = self; Thanks.SanitLee

1 Answers

0
votes

Credit to @Anna, add the line below to - (void)configureView

self.mapView.delegate = self;