MKAnnotationView custom image is not shown

2019-05-16 09:40发布

问题:

I am trying to add a custom image instead of the regular pin on the map. But it remains a red pin... What am I missing?

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{  
    static NSString* AnnotationIdentifier = @"AnnotationIdentifier";
    MKPinAnnotationView *annView = [[MKPinAnnotationView alloc]     initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier];
    annView.animatesDrop = TRUE;
    annView.image = [UIImage imageNamed:@"CustomPin.png"];
    return annView;
}

回答1:

MKMapView: Instead of Annotation Pin, a custom view

-(MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation 
{
    MKAnnotationView *pinView = nil; 
    if(annotation != mapView.userLocation) 
    {
        static NSString *defaultPinID = @"com.invasivecode.pin";
        pinView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
        if ( pinView == nil ) 
            pinView = [[MKAnnotationView alloc]
                                         initWithAnnotation:annotation reuseIdentifier:defaultPinID];

        //pinView.pinColor = MKPinAnnotationColorGreen; 
        pinView.canShowCallout = YES;
        //pinView.animatesDrop = YES;
        pinView.image = [UIImage imageNamed:@"pinks.jpg"];    //as suggested by Squatch
    } 
    else {
        [mapView.userLocation setTitle:@"I am here"];
    }
    return pinView;
}


回答2:

Hi just remove one line from your code... annView.animatesDrop = TRUE;

Remain Code-

-(MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{  
    static NSString* AnnotationIdentifier = @"AnnotationIdentifier";
    MKPinAnnotationView *annView = [[MKPinAnnotationView alloc]     initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier];
    annView.image = [UIImage imageNamed:@"CustomPin.png"];
    return annView;
}  


回答3:

I found it helpful to look at Apples Documentation and download the sample code.

http://developer.apple.com/library/ios/#samplecode/MapCallouts/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009746

They are implementing a custom annotation for their map.