问题描述
我一直在尝试对注释进行PerformSegue,但是此代码生成了不同的索引,并且detailsView中显示了错误的位置.找出解决此问题的方法将非常好.
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.
谢谢
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)
}
}
推荐答案
我认为这里的主要问题是您希望mapView.annotations
返回一个数组,其中所有注释的顺序与您的detailsDict
-Array相同.我认为这个假设容易出错,因为它很大程度上取决于MapKit框架的内部实现.
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.
更好的方法是将Dictionary条目与您添加到地图的PlaceAnnotation
一起存储:
A better way would be storing the Dictionary entry together with the PlaceAnnotation
that you add to the map:
- 将新属性
details
添加到类PlaceAnnotation
- 在创建
PlaceAnnotation
时设置 - 在
calloutAccessoryControlTapped
中,从PlaceAnnotation取回details属性. - 将此值传输到详细信息控制器(也许通过您的
selectedPlace
属性,但是我更希望直接实例化ViewController并设置该值).
details
值- 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).
这篇关于查找注释MapKit的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!