为 MapKit 中的每个注释添加 Id

Ahm*_*yed 6 annotations mapkit swift

我需要为地图中的每个注释添加一个 Id 以通过单击注释中的信息按钮打开新的视图控制器,我的问题是准备和执行 segue,我创建了它,但我不知道如何将 id 传递给赛格。

我为注释创建了子类来存储来自 JSON 的 ID

那是我的代码的一部分:

从 JSON 获取所有数据:

for location in self.locations {

  let annotation:MyAnnotation = MyAnnotation()
  annotation.title = location["truck_name"] as? String
  annotation.customTruckId = location["truck_id"] as? String
  annotation.coordinate = CLLocationCoordinate2D(latitude: (location["coor_x"] as! NSString).doubleValue, longitude: (location["coor_y"] as! NSString).doubleValue)
  self.AllMapView.addAnnotation(annotation)

  }
Run Code Online (Sandbox Code Playgroud)

我创建的子类:

class MyAnnotation : MKPointAnnotation {
    var customTruckId : String?
}
Run Code Online (Sandbox Code Playgroud)

问题就在这里:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "ShowTruckFromMap") {

            let des_VC = segue.destination as! TruckDetailsVC

            des_VC.truck_id = "How to get Id here !"
        }
    }


    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
        if control == view.rightCalloutAccessoryView {

            performSegue(withIdentifier: "ShowTruckFromMap", sender: self)
        }
    }
Run Code Online (Sandbox Code Playgroud)

谢谢

TOU*_*sim 3

您可以在不使用 Segue 的情况下显示 UIViewController。您必须首先在 UIViewController 中添加一个标识符:identity Inspector -> Identity -> Storyboard ID = TruckDetailsVCIdentifier

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
        if control == view.rightCalloutAccessoryView {
           let mainStoryboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
           let desController = mainStoryboard.instantiateViewController(withIdentifier: "TruckDetailsVCIdentifier") as! TruckDetailsVC
           let TruckAnnotation = view.annotation as? MyAnnotation
           desController.truck_id = (TruckAnnotation?.customTruckId!)!
           show(desController, sender: self)

        }
    }
Run Code Online (Sandbox Code Playgroud)