Pao
Pao

Reputation: 206

MKPinAnnotationView pinColor

I can't figure out why a MKPinAnnotationView associated (in theory) with a MKPointAnnotation doesn't appear on the map. In fact, the pin appears but it isn't purple as it should be...

Here is the code:

MKPointAnnotation *myPersonalAnnotation= [[MKPointAnnotation alloc]init];
myPersonalAnnotation.title= [appDelegate.theDictionary objectForKey:@"theKey"];
myPersonalAnnotation.coordinate=CLLocationCoordinate2DMake(6.14, 10.7);
MKPinAnnotationView *myPersonalView=[[MKPinAnnotationView alloc] initWithAnnotation:myPersonalAnnotation reuseIdentifier:@"hello"];
myPersonalView.pinColor=MKPinAnnotationColorPurple;
[myMap addAnnotation:myPersonalAnnotation];

Upvotes: 3

Views: 3191

Answers (1)

user467105
user467105

Reputation:

If you want to create an annotation view different from the default red pin, you have to create and return it in the map view's viewForAnnotation delegate method.

The map will automatically call the viewForAnnotation delegate method whenever it needs to show some annotation (either the built-in user location or annotations you add).

Remove the local creation of myPersonalView from before the call to addAnnotation and implement the viewForAnnotation method instead.

For example:

//in your current method...
MKPointAnnotation *myPersonalAnnotation= [[MKPointAnnotation alloc]init];
myPersonalAnnotation.title= [appDelegate.theDictionary objectForKey:@"theKey"];
myPersonalAnnotation.coordinate=CLLocationCoordinate2DMake(6.14, 10.7);
[myMap addAnnotation:myPersonalAnnotation];

//...

//add the viewForAnnotation delegate method...
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    //if annotation is the user location, return nil to get default blue-dot...
    if ([annotation isKindOfClass:[MKUserLocation class]])
        return nil;

    //create purple pin view for all other annotations...
    static NSString *reuseId = @"hello";

    MKPinAnnotationView *myPersonalView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseId];
    if (myPersonalView == nil)
    {
        myPersonalView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId];
        myPersonalView.pinColor = MKPinAnnotationColorPurple;
        myPersonalView.canShowCallout = YES;
    }
    else
    {
        //if re-using view from another annotation, point view to current annotation...
        myPersonalView.annotation = annotation;
    }

    return myPersonalView;
}


Make sure the map view's delegate property is set otherwise the delegate method won't get called.
In code, use myMap.delegate = self; (eg. in viewDidLoad) or make the connection in Interface Builder if myMap is an IBOutlet.

Upvotes: 2

Related Questions