点击注释时显示另一个视图

问题描述 投票:0回答:1

我创建了一个 UIViewRepresantable 来在 SwiftUI 中显示地图。我想在点击注释后显示一个叠加层,其中显示有关地图注释的信息。在协调器内部,我尝试使用 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)
       
    }
}

我尝试点击注释,但没有任何反应

swift swiftui mkmapview mkannotationview
1个回答
0
投票

您使用了错误的实例方法。尝试这样的 calloutAccessoryControlTapped

func mapView(
  _ mapView: MKMapView,
  annotationView view: MKAnnotationView,
  calloutAccessoryControlTapped control: UIControl
) { }
© www.soinside.com 2019 - 2024. All rights reserved.