iosswiftmapkituicontrol

Detect on calloutAccessoryControlTapped only the tap on rightCalloutAccessoryView


My calloutAccessoryControlTapped is also called when I just tap on annotation view and this behavior it's right. But how can I detect if the user has tapped on the right accessory view (in my case a detail disclosure button) and not just in the view?

I added a simple check but it doesn't work.

import UIKit
import MapKit

extension MapVC: MKMapViewDelegate, CLLocationManagerDelegate
{    
    func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl)
    {
        if control == view.rightCalloutAccessoryView
        {
            ... // enter here even if I tapped on the view annotation and not on button
        }
    }

}

Solution

  • To achieve it you would need to add target for the right accessory view. You can achieve it by setting button to rightCalloutAccessoryView as shown in the code snippet.

    class MapViewController: UIViewController, MKMapViewDelegate {
    
        func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
            if annotation is Annotation {
                let annotationView = AnnotationView(annotation: annotation, reuseIdentifier: "reuseIdentifier")
                let rightButton = UIButton(type: .DetailDisclosure)
                rightButton.addTarget(self, action: #selector(didClickDetailDisclosure(_:)), forControlEvents: .TouchUpInside)
                annotationView.rightCalloutAccessoryView = rightButton
            }
            return nil
        }
    
        func didClickDetailDisclosure(button: UIButton) {
            // TODO: Perform action when was clicked on right callout accessory view.
        }
    }
    
    // Helper classes.
    class Annotation: NSObject, MKAnnotation {
        var coordinate: CLLocationCoordinate2D
        var title: String?
        var subtitle: String?
    
        init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) {
            self.coordinate = coordinate
            self.title = title
            self.subtitle = subtitle
        }
    }
    
    class AnnotationView: MKAnnotationView {
    
    }