I have created a UIViewRepresantable to display a map in SwiftUI. I want display an overlay displaying information about the annotation to the map, once the annotation is tapped. Inside the Coordinator I am trying to use the didSelect method. Right now I am just trying to print "Tapped". But it just doesnt show anything. Anyone know what I might be missing?
My Code:
import Foundation
import SwiftUI
import MapKit
class Coordinator: NSObject, MKMapViewDelegate {
var control: MapViews
init(_ control: MapViews){
self.control = control
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
// 1
guard annotation is LandmarkAnnotation else { return nil }
// 2
let identifier = "id"
// 3
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
if annotationView == nil {
//4
annotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView?.canShowCallout = true
// 5
let btn = UIButton(type: .detailDisclosure)
annotationView?.rightCalloutAccessoryView = btn
} else {
// 6
annotationView?.annotation = annotation
}
return annotationView
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
print("Tapped")
}
}
struct MapViews: UIViewRepresentable{
let landmarks: [Landmark]
func makeUIView(context: Context) -> MKMapView {
let map = MKMapView()
map.showsUserLocation = true
map.userTrackingMode = .follow
map.delegate = context.coordinator
return map
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func updateUIView(_ uiView: MKMapView, context: UIViewRepresentableContext <MapViews>) {
updateAnnotations(from: uiView)
}
func updateAnnotations(from mapView: MKMapView){
let annotations = self.landmarks.map(LandmarkAnnotation.init)
mapView.addAnnotations(annotations)
}
}
I tried to tap the annotation, but nothing happens
You're using the wrong instance method. Try calloutAccessoryControlTapped like this: