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

Upvotes: 4

Views: 5749

Answers (2)

Lu_
Lu_

Reputation: 2685

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

Upvotes: 1

Rob
Rob

Reputation: 437372

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.

Upvotes: 12

Related Questions