MantisShrimp
MantisShrimp

Reputation: 171

Why is my custom annotation image not showing up?

I am trying to change the image of the pin through the viewForAnnotation method. This is the code I have:

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {

    if annotation.isMemberOfClass(MKUserLocation.self) {
        return nil
    }

    let reuseId = "pin"

    var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
    if pinView == nil {
        pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        pinView!.canShowCallout = true
        pinView!.animatesDrop = false
        pinView!.image = UIImage(named: "marker.png")
    }
    else {
        pinView!.annotation = annotation
    }

    return pinView

}

When I run the project, the image does not show up. What am I doing wrong?

Upvotes: 0

Views: 1257

Answers (1)

baydi
baydi

Reputation: 1003

Try this code it will help.

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {

if annotation.isMemberOfClass(MKUserLocation.self) {
    return nil
}

let reuseId = "MKAnnotationView"

var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKAnnotationView
if pinView == nil {
    pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)}
    pinView!.canShowCallout = true
    pinView!.animatesDrop = false // i am not sure about this line so must try this by commenting
    pinView!.image = UIImage(named: "marker.png") // make sure this name is the name of image

return pinView

}

it will help.

Upvotes: 1

Related Questions