3

I am trying to set an image instead of a pin on a map using MapKit. I know I have to set a custom MKAnnotationView. Therefore I should implement the following lines:

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

    let reuseId = "test"

    var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
    if anView == nil {
        anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        anView.canShowCallout = true
    }
    else {
        anView.annotation = annotation
    }

    //Set annotation-specific properties **AFTER**
    //the view is dequeued or created...

    let cpa = annotation as CustomPointAnnotation
    anView.image = UIImage(named:cpa.imageName)

    return anView
}

But it is simply not working in my code. I copy/pasted all the code from this post, adding an image called 1.png to my supporting file. But the map displays a red pin instead of the 1.png image.

It looks like the whole mapView function is useless. Do I have to call it in viewDidLoad? How am I supposed to make it being used? Also, what is the reuseId for? Where should I call it?

Thank you for your answers and happy new year.

Community
  • 1
  • 1
Quentin Malgaud
  • 405
  • 6
  • 21
  • 1
    Did you set the `delegate` of the `MKMapView` to `self` in your view controller? – akashivskyy Jan 02 '15 at 10:42
  • (Or set the `delegate` to be the view controller when you designed this scene in Interface Builder?) – Rob Jan 02 '15 at 10:49
  • Thank you so much guys! I've spend the whole year looking for the answer. The picture finally appeared. It is now gigantic but I'll see if I can edit the frame. If not I'll edit the picture itself. Thank you. – Quentin Malgaud Jan 02 '15 at 11:38

1 Answers1

2

Be sure that the MKMapView's delegate is properly linked to the ViewController that implements that method.

You could do this in the "viewWillAppear" method like this: mapView.delegate = self;

Or in the InterfaceBuilder: - Be sure that your MapKit View is selected - Go to the "Connections Inspector" - In the "Outlets" section, Drag and drop the "delegate" attribute to the ViewController that implements the delegate method

mauricioconde
  • 5,032
  • 3
  • 28
  • 24