gpt4 book ai didi

ios - 需要帮助将 mapKit 注释链接到 Swift 中的 CollectionView

转载 作者:可可西里 更新时间:2023-11-01 01:22:35 26 4
gpt4 key购买 nike

我正在快速构建一个在同一页面上具有 Collection View 和 map View 的应用程序。用户可以滚动浏览 Collection View 以查看优惠(这是该应用程序的目的), map View 填充有注释图钉,显示 map 上优惠的物理位置。

我的问题是我发现很难将 Collection View 单元格链接到正确的注释。

我将注释添加到 map 中,如下所示:

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)

}

然后我可以滚动浏览 Collection View 单元格

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell


// Connect cell to the linked annotation

// ** This links to a random annotation, but not the correct one - need help on this please **
self.mapView.selectAnnotation(self.mapView.annotations[row], animated: true)

}

如果有人可以帮助我了解如何将 Collection View 链接到正确的 map 注释,我将非常有帮助。我只知道 swift (一点点),所以希望能以这种语言提供帮助。谢谢

最佳答案

如果您希望事件 map 注释在您滚动时发生变化,并且您希望将垂直居中的集合单元格视为当前显示的 - 这是我想出的方法。

注意:我没有测试,这只是基本思路

func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView is 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 is no cell in the center of collection view (you might want to think what you want to do in this case)
return
}

if let selectedAnnotation = mapView.selectedAnnotations.first {
// Ignore if correspondent annotation is already selected
if selectedAnnotation.isEqual(self.mapView.annotations[path.row]) {
self.mapView.selectAnnotation(self.mapView.annotations[path.row], animated: true)
}
}
}
}

关于ios - 需要帮助将 mapKit 注释链接到 Swift 中的 CollectionView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43241675/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com