-1

I have two buttons on the two sides of my annotationView and would like them to execute different methods depending on which one is clicked. I used the calloutAccessoryControlTapped for the first button, but do not know how to specify a method for the second one (button2). Any help would be greatly appreciated.

Thanks

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        // Define a reuse identifier just like with tables or collection views
        let identifier = "Capital"

        if annotation is Capital {
            var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView

            if annotationView == nil {
                // If it isn't able to find a reusable view, create a new one using MKPinAnnotationView and sets its canShowCallout property to true. This triggers the popup with the city name.
                annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
                annotationView!.canShowCallout = true

                let button = UIButton(type: .detailDisclosure)
                annotationView!.rightCalloutAccessoryView = button

                let button2 = UIButton(type: .contactAdd)
                annotationView?.leftCalloutAccessoryView = button2

            } else {
                annotationView!.annotation = annotation
            }
             return annotationView
        }
        return nil
    }

    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {


        let capital = view.annotation as! Capital
        let placeName = capital.title
        let placeInfo = capital.info

        // let fullImage = UIImage(named: "fullHeart")
        // let emptyImage = UIImage(named: "emptyHeart")

        let ac = UIAlertController(title: placeName, message: placeInfo, preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)


    }

1 Answers1

0

Try the following code

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
    if control == view.rightCalloutAccessoryView {
        // rightCalloutAccessoryView tapped
    } else if control == view.leftCalloutAccessoryView {
        // leftCalloutAccessoryView tapped
    }
}
Kosuke Ogawa
  • 7,383
  • 3
  • 31
  • 52