Search code examples
iosswiftannotationsmkmapviewmkannotationview

How to link an annotation in MapView to its calling pin


Swift 4 iOS 11.x

Learning about mapViews and annotations and I can quite get my mind around some functionality I would like to do.

I create a mapView, and I add an annotation to it with a button, so far so good. I want the button to be a delete pin one, so it looks like this.

enter image description here

Now when I click on the blue no entry I want it to delete the black pin that it is connected too. But how to trace the link of the annotation to its pin. I get a call back with the button and thru the accessory view. I can lookup the title of the view and find the link, but surely there is a better method.


Solution

  • You need to use this method func mapView(_ mapView: MKMapView,annotationView view: MKAnnotationView,calloutAccessoryControlTapped control: UIControl) of MKMapViewDelegate

    Something like this

    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView,
                 calloutAccessoryControlTapped control: UIControl) {
    
        //Here you have the annotation that was selected
        let selectedAnnotation = view.annotation
        //Do whatever you need here
    }