Search code examples
iosswiftmkmapviewmkannotation

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"))
}

Solution

  • 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.