gpt4 book ai didi

swiftui - 如何为 SwiftUI ViewRepresentable 自定义 MKMapView 委托(delegate)操作?

转载 作者:行者123 更新时间:2023-12-05 06:06:32 24 4
gpt4 key购买 nike

我在 ViewRepresentable 中包装了一个 MKMapView

public struct MapView: UIViewRepresentable {

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

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?

}
}

最佳答案

这是一个解决方案 - 为 View 引入回调属性并将其注入(inject)到您的 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)
}

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 !!
}
}
}

关于swiftui - 如何为 SwiftUI ViewRepresentable 自定义 MKMapView 委托(delegate)操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65720037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com