【发布时间】:2021-11-02 17:46:21
【问题描述】:
我正在使用 SwiftUI 并使用 MKMapView 在视图上显示地图、注释和叠加层。
我使用的是新的Map(),但由于缺乏覆盖支持,我又回到了 UIKit Representable。
当我使用Map 时,添加注释很容易,但是当使用UIKitRepresentable 时,我对将数据放在哪里以及如何从网络调用中提取的数组进行注释有点困惑。
我读过的所有内容要么是在 Obj-C 中,要么是添加了一个注释点。我正在尝试添加(目前约为 800 个),这就是为什么我想利用 MKMapView 的可重用性和集群性。
这是我目前拥有的:
struct UIMapView: UIViewRepresentable {
@EnvironmentObject var dataModel: DataModel
@EnvironmentObject var mapViewModel: MapViewModel
func makeCoordinator() -> Coordinator { Coordinator() }
func makeUIView(context: Context) -> MKMapView {
let view = mapViewModel.mapView
drawOverlayRing(view: view)
view.delegate = context.coordinator
return view
}
func updateUIView(_ uiView: MKMapView, context: Context) {}
class Coordinator: NSObject, MKMapViewDelegate {
func mapView(_ map: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation { return nil }
let identifier = "pinAnnotation"
var annotationView = map.dequeueReusableAnnotationView(
withIdentifier: identifier
) as? MKPinAnnotationView
if annotationView == nil {
annotationView = MKPinAnnotationView(
annotation: annotation,
reuseIdentifier: identifier
)
annotationView?.canShowCallout = true
} else {
annotationView?.annotation = annotation
}
return annotationView
}
}
func getAnnotations(view: MKMapView) {
for location in dataModel.locations {
let annotation = MKPointAnnotation()
annotation.title = location.title
annotation.coordinate = CLLocationCoordinate2D(
latitude: location.latitude,
longitude: location.longitude
)
view.addAnnotation(annotation)
}
}
}
【问题讨论】:
标签: swift swiftui mapkit mapkitannotation