ios - Need help linking mapKit annotation to CollectionView in Swift -


i'm building app in swift has collection view , map view on same page. user can scroll through collection view see offers (this purpose of app) , map view populated annotation pins displaying physical location of offers on map.

my issue i'm finding hard link collection view cell correct annotation.

i add the annotations map below:

for location in self.querydatamapannotations {             let annotation = mkpointannotation()             annotation.title = location["title"] as? string             annotation.subtitle = location["distance"] as? string             annotation.coordinate = cllocationcoordinate2d(latitude: location["latitude"] as! double, longitude: location["longitude"] as! double)             self.mapview.addannotation(annotation)          } 

i can scroll through collection view cells

func collectionview(_ collectionview: uicollectionview, cellforitemat indexpath: indexpath) -> uicollectionviewcell {          // reference our storyboard cell         let cell = collectionview.dequeuereusablecell(withreuseidentifier: reuseidentifier, for: indexpath indexpath) as! mycollectionviewcell           // connect cell linked annotation           // ** links random annotation, not correct 1 - need on please **          self.mapview.selectannotation(self.mapview.annotations[row], animated: true)      } 

if 1 me on how link collection view correct map annotation, helpful. know swift (a little) appreciate in language.

if want active map annotations change scroll, , want consider vertically centred collection cell displayed — here way came with.

note: didn't test it, it's basic idea

func scrollviewdidscroll(_ scrollview: uiscrollview) {     if scrollview uicollectionview {         let collectionviewcenter = cgpoint(x: collectionview.bounds.size.width / 2 + collectionview.contentoffset.x, y: collectionview.bounds.size.height / 2 + collectionview.contentoffset.y)         let centredcellindexpath = collectionview.indexpathforitem(at: collectionviewcenter)          guard let path = centredcellindexpath else {             // there no cell in center of collection view (you might want think want in case)             return         }          if let selectedannotation = mapview.selectedannotations.first {             // ignore if correspondent annotation selected             if selectedannotation.isequal(self.mapview.annotations[path.row]) {                 self.mapview.selectannotation(self.mapview.annotations[path.row], animated: true)             }         }     } } 

Comments