Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Changing Annotation Image Not Working

I have followed other stack posts and tutorials in changing my annotations image to a custom one, but it does not seem to work. No errors or runtime errors appear, it's just that the annotation image does not change.

Just by the way I set a break point on the line annotationView!.image = UIImage(named: "RaceCarMan2png.png") and it shows that the line is being called, but yet nothing happens. I would really appreciate your help. Thanks.

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation {
        return nil
    }

    let identifier = "MyCustomAnnotation"

    var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier)
    if annotationView == nil {
        annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
        annotationView?.canShowCallout = true

        annotationView!.image = UIImage(named: "RaceCarMan2png.png")

    } else {
        annotationView!.annotation = annotation
    }


    configureDetailView(annotationView!)

    return annotationView
}

func configureDetailView(annotationView: MKAnnotationView) {
        annotationView.detailCalloutAccessoryView = UIImageView(image: UIImage(named: "url.jpg"))
}
like image 557
Stephane Hatgis-Kessell Avatar asked Dec 11 '22 15:12

Stephane Hatgis-Kessell


2 Answers

The issue is that you're using MKPinAnnotationView. If you use MKAnnotationView, you will see your image.

In the past (e.g. iOS 8), setting the image of MKPinAnnotationView seemed to work fine, but in iOS 9 and later, it uses a pin, regardless (which is not entirely unreasonable behavior for a class called MKPinAnnotationView; lol).

Using MKAnnotationView avoids this problem.

like image 117
Rob Avatar answered Jan 04 '23 10:01

Rob


Call that before return

if let annotationView = annotationView {
    // Configure your annotation view here
    annotationView.image = UIImage(named: "RaceCarMan2png.png")
}

return annotationView

and check with breakpoint if it is ok inside if

like image 37
Lu_ Avatar answered Jan 04 '23 11:01

Lu_