2017-06-28 53 views
3

我需要爲地圖中的每個註解添加一個Id,以通過單擊註釋中的info按鈕打開新的視圖控制器,我的問題是準備並執行segue,我創建了它,但我不不知道如何將ID傳遞給segue。爲MapKit中的每個註解添加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) 

    } 

子我創建的類:

class MyAnnotation : MKPointAnnotation { 
    var customTruckId : String? 
} 

問題在於segue:

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

感謝

回答

2

你可以展示你的UIViewController不使用Segue公司。 你必須首先把標識您的UIViewController中: 身份檢查 - >標識 - >故事板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) 

     } 
    } 
+0

謝謝,但問題是如何獲得'truck_id'並將它傳遞給註釋 –

+0

歡迎您:) –

1

我找到了答案:

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: "TruckDetailsVC") as! TruckDetailsVC 

      let TruckAnnotation = view.annotation as? MyAnnotation 

      desController.truck_id = (TruckAnnotation?.customTruckId!)! 

      show(desController, sender: self) 

     } 
    } 

感謝所有

+0

這就是我在我的答案中告訴您的! –

+0

我的問題是如何在segue或其他方法中動態獲取id,我也用segue來完成,謝謝你的幫助 –