Setting custom image - MKPinAnnotationView - Swift 3

3.1k Views Asked by At

I'm using MapKit and I'm currently trying to set a custom pin annotation image on my pins. However, I'm having a hard time figuring out why it doesn't work. All of the other code is working perfectly, and when I try printing the frame of the image after setting it, it does show the correct dimensions for my "pinImage", so it seems to be able to set the image on the property.

Also, the delegate is set correctly, this is verified by setting a custom color on the default pin.

I've also tried using "pinImage.png", without luck. And since MKPinAnnotationView is a subclass of MKAnnotationView, I see no problem with why that should be the issue, and to be sure, I tried to use the MKAnnotationView also, without luck.

Here's my code:

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

    if let annotation = annotation as? Pin {
        let identifier = LocalConstants.pinIdentifier
        var view: MKPinAnnotationView
        if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView {
            dequeuedView.annotation = annotation
            view = dequeuedView
        } else {

            view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
            view.canShowCallout = true
            view.calloutOffset = CGPoint(x: -5, y: 5)
            let detailButton = UIButton(type: .detailDisclosure) as UIView
            view.rightCalloutAccessoryView = detailButton
            //view.pinTintColor = Util.Colors.pluppPurple
        }
        view.image = UIImage(named: "pinImage")
        return view
    }

Thanks in advance!

1

There are 1 best solutions below

0
fritiof On BEST ANSWER

The answer was indeed to use MKAnnotationView and not MKPinAnnotationView. I do not know what I messed up when trying it out yesterday. Final working copy below, for future reference:

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

    if let annotation = annotation as? Pin {
        let identifier = LocalConstants.pinIdentifier
        var view: MKAnnotationView

        if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) {
            dequeuedView.annotation = annotation
            view = dequeuedView
        } else {
            view = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
            view.canShowCallout = true
            view.calloutOffset = CGPoint(x: -5, y: 5)
            view.tintColor = Util.Colors.pluppGrey

            let detailButton = UIButton(type: .detailDisclosure) as UIView
            view.rightCalloutAccessoryView = detailButton
        }
        view.image = UIImage(named: LocalConstants.pluppPin)
        return view
    }
    return nil
}