Find index of annotation MapKit

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-08 10:28:10

问题


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



回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!