iosswiftmkmapviewaccessoryview

MKMapView detecting left or right


iOS 11.x Swift 4.0

Learning about mapview and created a pin with left and right accessoryviews with this code.

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

    if annotation is MKUserLocation  {
        return nil
    }

    let reuseId = "pin"
    var pav:MKPinAnnotationView?
    if (pav == nil)
    {
        pav = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        pav?.isDraggable = true
        pav?.canShowCallout = true;
        pav?.rightCalloutAccessoryView = UIButton(type: .infoLight)
        pav?.leftCalloutAccessoryView = UIButton(type: .contactAdd)
    }
    else
    {
        pav?.annotation = annotation;
    }

    return pav;
}

Using this call to detect when you press on the infoLight and/or the contactAdd UIButtons. But I struggling to figure out how to tell which one was pressed? This call fires? But how to figure if it was the left or the right?

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
    print("go figure annotationView \(view)")
    if (view.rightCalloutAccessoryView != nil) {
        print("right \(view.rightCalloutAccessoryView)")
    }
}

Obviously this is wrong, but how to know if the left or the right was tapped?


Solution

  • Try following code:

    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
        if view.rightCalloutAccessoryView == control {
            //right accessory
        } else {
            // left Accessory
        }
    }