I need to add an Id for each annotation in map to open new view controller by clicking on info button in annotation , my problem is in prepare and perform segue, I created it, but I don't know how to pass the id to the segue.
I created sub class for annotation to store the ID that comes from JSON
Thats parts of my code :
Getting all data from 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)
}
Sub class I created:
class MyAnnotation : MKPointAnnotation {
var customTruckId : String?
}
Problem is here in 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)
}
}
Thanks
You can show your UIViewController without using Segue. You must at first put an identifier to your UIViewController in : 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)
}
}
I found Answer:
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)
}
}
Thanks for all
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With