Custom annotationView images revert to pins when clicked

时光毁灭记忆、已成空白 提交于 2019-12-11 03:11:27

问题


I'm displaying custom images on a map (instead of the default pins) using the code below. However, when I tap on an item (and the callout appears), the image reverts to the default red pin. How can I keep my custom image, even when the callout is displayed?

- (MKAnnotationView *) mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation
{
    MKPinAnnotationView *pinAnnotation = nil;

    if (annotation != mapView.userLocation) 
    {
        static NSString *pinID = @"mapPin";
        pinAnnotation = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pinID];
        if (pinAnnotation == nil)
            pinAnnotation = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pinID] autorelease];

        // Set the image
        pinAnnotation.image = [UIImage imageNamed:@"TestIcon.png"];

        // Set ability to show callout
        pinAnnotation.canShowCallout = YES;

        // Set up the disclosure button on the right side
        UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        pinAnnotation.rightCalloutAccessoryView = infoButton;

        [pinID release];
    }

    return pinAnnotation;
    [pinAnnotation release];
}

回答1:


I found by making the pinAnnotation a MKAnnotationView rather than a MKPinAnnotationView, I got the desired result. Image doesn't turn into a pin anymore

    static NSString *pinID = @"mapPin";
    pinAnnotation = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pinID];
    if (pinAnnotation == nil)
        pinAnnotation = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pinID] autorelease];

    // Set the image
    pinAnnotation.image = [UIImage imageNamed:@"TestIcon.png"];



回答2:


You need to use a subview rather than the image property. This code succssfully solves the problem for me:

    UIImage * image = [UIImage imageNamed:@"blue_pin.png"];
    UIImageView *imageView = [[[UIImageView alloc] initWithImage:image] autorelease];
    [annView addSubview:imageView];


来源:https://stackoverflow.com/questions/2576211/custom-annotationview-images-revert-to-pins-when-clicked

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