Can't select MKViewAnnotation twice?
Asked Answered
V

2

10

I've got pins placed on a map and when I tap on them I'm calling the didSelect. The function only gets called the first time the pin is tapped, and after that it's not called on that same pin again unless I select another pin and then come back and tap it.

What that sounds like to me is the pin is being selected, and didSelect can only be called in unselected pins, so when I go tap on another pin it's deselecting the first pin and making it tappable again.

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    view.isSelected = false
}

I don't understand why the above code does not work.

How can I allow my annotations be tapped more than one time in a row?

Voss answered 6/8, 2017 at 6:31 Comment(1)
"I don't understand why the above code does not work." ... See the documentation that warns that one should not select/deselect the annotation views directly: "You should not call this method directly. An MKMapView object calls this method in response to user interactions with the annotation." Use deselectAnnotation on the annotation, and let the map view take care of the annotation views itself.Swoon
C
17

Try with this method deselectAnnotation

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
     //do what you need here
     mapView.deselectAnnotation(view.annotation, animated: true)
}

Hope this helps

Crosseye answered 6/8, 2017 at 7:49 Comment(2)
Thank you, appreciate itVoss
Thanks. Works like a charm!Emphatic
S
2

There is another option, and that is to add a Gesture Recognizer for on the annotationView. This will enable showing the callout view (since de-selecting the annotation immediately will not show it).

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

    view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(mapPinTapGestureRecognizer)))
}

@objc private func mapPinTapGestureRecognizer(gestureRecognizer: UITapGestureRecognizer) {

    // Will get called on the second time the pin is selected.
    // And then, after that, it will be called every time.
}

Just don't forget to remove the recognizer when the annotation is no longer selected.

internal func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {

    // Remove the gesture recognizer when the annotation is no longer selected.
}
Siward answered 13/9, 2017 at 13:51 Comment(2)
why the downvote? need some feedback to the answer so that it can be improved.Siward
Solution is valid because the func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) can only be used one time. For deselecting this option is only validResource

© 2022 - 2024 — McMap. All rights reserved.