如何为 SwiftUI ViewRepresentable 制作自定义 MKMapView 委托操作?

我将 MKMapView 包裹在 ViewRepresentable

public struct MapView: UIViewRepresentable {

我想创建一个像这样工作的动作回调:

MapView().onAnnotationTapped { annotation in
   
}

MapView中我已经定义了

@inlinable public func onAnnotationTapped(site: (AnnotationView) -> ()) -> some View {
    return self
}

但是如何从协调员那里提供AnnotationView

public class MapViewCoordinator: NSObject,mkmapviewdelegate {
    var mapView: MapView
    
    init(_ control: MapView) {
        self.mapView = control
    }
    
    public func mapView(_ mapView: MKMapView,didSelect view: MKAnnotationView) {

  /// How to send from here to the MapView function? 

    }
} 
           
a2969318 回答:如何为 SwiftUI ViewRepresentable 制作自定义 MKMapView 委托操作?

这是一个解决方案 - 为视图引入回调属性并将其注入您的 inalinable 修饰符。使用 Xcode 12.1 / iOS 14.1 准备

struct MapView: UIViewRepresentable {
    func makeUIView(context: Context) -> MKMapView {
        let view = MKMapView()
        view.delegate = context.coordinator
        return view
    }
    
    func updateUIView(_ uiView: MKMapView,context: Context) {
    }

    func makeCoordinator() -> MapViewCoordinator {
        MapViewCoordinator(self)
    }
    
    private var tapCallback: ((MKAnnotationView) -> ())?    // << this one !!
    
    @inlinable public func onAnnotationTapped(site: @escaping (MKAnnotationView) -> ()) -> some View {
        var newMapView = self
        newMapView.tapCallback = site            // << here !!
        return newMapView
    }
    
    public class MapViewCoordinator: NSObject,MKMapViewDelegate {
        var mapView: MapView
        
        init(_ control: MapView) {
            self.mapView = control
        }
        
        public func mapView(_ mkMap: MKMapView,didSelect view: MKAnnotationView) {
            self.mapView.tapCallback?(view)     // << call !!
        }
    }
}
本文链接:https://www.f2er.com/1102915.html

大家都在问