Retrieving information from the array that mounted

2019-09-11 19:35发布

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条回答
地球回转人心会变
2楼-- · 2019-09-11 19:42

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])
    } 
}
查看更多
登录 后发表回答