我创建了一个UIViewRepresantable来在SwiftUI中显示Map。我想显示一个覆盖图,显示有关Map注解的信息(单击注解后)。在Coordinator中,我尝试使用didSelect方法。现在我只是想打印“Tapped”。但它只是没有显示任何东西。有人知道我可能错过了什么吗?
我的代码:
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)
}
}
我试着点击注解,但什么也没发生
1条答案
按热度按时间cgvd09ve1#
您使用了错误的示例方法。试试calloutAccessoryControlTapped: