I'm trying to get the MKAnnotationView that displays the user location (blue dot) in MapKit to add a custom gesture recognizer. Is this possible?
I've tried via the delegate method but I don't know how to dequeue the view when I don't have the identifier string. If I had the identifier I could probably do something like the code below;
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
let userLocationAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "??", for: annotation)
userLocationAnnotationView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.handleStuff)))
return userLocationAnnotationView
}
}
EDIT
Ah, been stuck on this for hours and found the solution directly after I posted. I found two different ways of solving it with delegate methods. The first way could be via didSelect:
func mapView(_ mapView: MKMapView,
didSelect view: MKAnnotationView){
if view.annotation is MKUserLocation {
// User clicked on the blue dot
}
}
Or if a gesture recognizer is needed it could be done as below. Should probably add a check if the gesture recognizer already have been added since this function gets called every time an annotation view is added.
func mapView(_ mapView: MKMapView,
didAdd views: [MKAnnotationView]){
for view in views {
if view.annotation is MKUserLocation {
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.handleStuff)))
}
}
}