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??
Asked
Active
Viewed 109 times
1 Answers
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])
}
}

Nirav D
- 71,513
- 12
- 161
- 183
-
Thank you. I will try this and later I will answer. – breno Feb 09 '17 at 11:55
-
I receive this error: "Could not cast value of type 'NSKVONotifying_MKUserLocation' (0x7c985000) to 'Floop.MyAnnotation'" – breno Feb 10 '17 at 19:47