微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 MapKit 中向地图添加注释的功能不起作用

如何解决在 MapKit 中向地图添加注释的功能不起作用

创建地图并向其添加注释的相关代码在这里

class LandmarkAnnotation: NSObject,MKAnnotation {
    let title: String?
    let subtitle: String?
    let coordinate: CLLocationCoordinate2D
init(title: String?,subtitle: String?,coordinate: CLLocationCoordinate2D) {
        self.title = title
        self.subtitle = subtitle
        self.coordinate = coordinate
    }
}


struct MapView: UIViewRepresentable {
    
    let landmarks = LandmarkAnnotation(title: "test",subtitle: "subtest",coordinate: CLLocationCoordinate2D(latitude: 37.786996,longitude: -122.419281))//.requestMockData()
    
    func makeCoordinator() -> MapViewCoordinator {
        MapViewCoordinator(self)
    }
    
    /**
     - Description - Replace the body with a make UIView(context:) method that creates and return an empty MKMapView
     */
    func makeUIView(context: Context) -> MKMapView{
        MKMapView(frame: .zero)
    }
    
    func updateUIView(_ view: MKMapView,context: Context){
        //If you changing the Map Annotation then you have to remove old Annotations
        //mapView.removeAnnotations(mapView.annotations)
        view.delegate = context.coordinator
        //This doesn't add annotations for some reason
        view.addAnnotations([landmarks])
        print(landmarks)
        //print returns <River_Watch.LandmarkAnnotation: 0x282758a80> for some reason
    }
}

/*
  Coordinator for using UIKit inside SwiftUI.
 */
class MapViewCoordinator: NSObject,MKMapViewDelegate {
    
      var mapViewController: MapView
        
      init(_ control: MapView) {
          self.mapViewController = control
      }
        
      func mapView(_ mapView: MKMapView,viewFor
           annotation: MKAnnotation) -> MKAnnotationView?{
         //Custom View for Annotation
          let annotationView = MKAnnotationView(annotation: annotation,reuseIdentifier: "customView")
          annotationView.canShowCallout = true
          //Your custom image icon
          annotationView.image = UIImage(named: "locationPin")
          return annotationView
       }
}

由于某种原因,变量“landmarks”的格式未正确添加为注释,当我打印该变量时,它返回了 <River_Watch.LandmarkAnnotation: 0x282758a80>,我认为这不是注释的正确格式。我哪里做错了?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。