Ivan Bliznyuk Ivan Bliznyuk - 4 years ago 139
Swift Question

Find index of annotation MapKit

I have been trying to performSegue for annotation, but this code generates different indexes and wrong places are shown in detailsView. Would be great to find out how it is possible to fix this.

Thanks

var detailsDict = [NSDictionary]()
var selectedPlace: NSDictionary!

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {

if (view.annotation?.isKind(of: PlaceAnnotation.self))! {
let annotation = view.annotation
let index = (self.mapView.annotations as NSArray).index(of: annotation!)
let place = detailsDict[index]
selectedPlace = place

performSegue(withIdentifier: "showMuseumDetails", sender: self)

}
}

Answer Source

I think the main problem here is that you expect that mapView.annotations returns an array with all annotations being in the same order as your detailsDict-Array. I think that this assumption is error prone, because it would highly depend on the internal implementation of the MapKit framework.

A better way would be storing the Dictionary entry together with the PlaceAnnotation that you add to the map:

  • Add a new property details to class PlaceAnnotation
  • Set details value when you create the PlaceAnnotation
  • in calloutAccessoryControlTapped, get back the details property from the PlaceAnnotation
  • transfer this value to detail controller (maybe via your selectedPlace property, but I would prefer in instatiating the ViewController directly and setting the value).
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download