问题
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)
}
}
回答1:
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 classPlaceAnnotation
- Set
details
value when you create thePlaceAnnotation
- 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).
回答2:
We can do it using this method
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
let annotation = view.annotation
let index = (self.mapView.annotations as NSArray).index(of: annotation!)
print ("Annotation Index = \(index)")
}
来源:https://stackoverflow.com/questions/42068857/find-index-of-annotation-mapkit