Detect Tap on CalloutBubble in MKAnnotationView

Viewed 13623

Im working with MKMapView and MKAnnotationView.

I have an annotation in the map. When the users tap on it, the callOut Bubble is displayed. When the annotation is tapped again ( and the callOut Bubble is visible ) i need to change to another view.

How can i detect the second tap, or the tap in the bubble?

7 Answers

Here is my solution to this question:

Swift 5

First, add MKMapViewDelegate method

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView)

This gets called when annotation is selected and the callout bubble is shown. You can extract the callout bubble view like this, and add the tap gesture recognizer to it, like so:

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    // Set action to callout view
    guard let calloutView = view.subviews.first else { return }
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(userDidTapAnnotationCalloutView(_:)))
    calloutView.addGestureRecognizer(tapGesture)
}

And handle tap action like this:

@objc
private func userDidTapAnnotationCalloutView(_ sender: UITapGestureRecognizer) {
    // Handle tap on callout here
}

This works in Swift 5.2

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    let gesture = UITapGestureRecognizer(target: self, action: #selector(calloutTapped))
    view.addGestureRecognizer(gesture)
}

@objc func calloutTapped() {
    
    print ("Callout Tapped")
    
}
Related