Retrieving information from the array that mounted the map (MapKit)

≡放荡痞女 提交于 2019-12-12 02:34:19

问题


I have an array with several dictionaries. In every dictionary I have some information. I want to add a point on the map for each item inside the array. I do not have anything but didSelectForAnnotation method, how do I get inside the array as certain information of that object? In a table I would use the indexPath but an annotation does not have that indexPath. Is there a solution??


回答1:


If you want to set custom information with you MKPointAnnotation then you need to subclass it and create a custom property that you can use latter to differentiate it from other array object.

class MyAnnotation: MKPointAnnotation {

     var arrayIndex: Int!
}

Now you need to create annotation with MyAnnotation class, and set the arrayIndex with your array index where you are creating annotation.

for (index,item) in yourArray.enumerated() {
    let annotation = MyAnnotation()

    //Set arrayIndex for your annotation
    annotation.arrayIndex = 1    

    //Set coordinate and title from your array
    annotation.coordinate = locations
    annotation.title = "Zaid Homes"
    annotation.subtitle = "Hay aljameaa"
    map.addAnnotation(annotation)
}

Now in didSelect view method of mapView you can get that index.

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    if let annotation = view.annotation as? MyAnnotation {
        print(annotation.arrayIndex)
        print(yourArray[annotation.arrayIndex])
    } 
}


来源:https://stackoverflow.com/questions/42135662/retrieving-information-from-the-array-that-mounted-the-map-mapkit

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