首页 > 解决方案 > 滚动单元格时如何使地图注释链接到ui集合单元格突出显示注释

问题描述

正如标题描述的问题,我不知道触发链接的功能或方法。

我已经将所有注释添加到地图中。

希望有人能给出具体的示例代码,谢谢。

标签: swiftscrolluicollectionviewannotations

解决方案


几个想法:

  1. 你有代码说:

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView is UICollectionView {
            let collectionViewCenter = CGPoint(x: myMap.bounds.size.width / 2 + myMap.frame.minX, y: myMap.bounds.size.height / 2 + myMap.frame.minY)
            let centredCellIndexPath = cafeCollectionView.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
            }
    
            // select annotation here, if needed
        }
    }
    

    您将 设置为地图collectionViewCenter的中心,但随后将其用作参数如果您尝试查找,则应使用集合视图的中心,而不是地图的中心。indexPathForItem(at:)centeredCellIndexPathbounds

    如果您的地图(如 AirBnb 应用程序)与集合视图的大小不同,您可能会尝试调用集合视图之外的indexPathForItem(at:),并且在这种情况下不会得到任何点击。CGPointbounds

    因此,例如,如果您想要集合视图的中心,您可以将collectionViewCenterassignment 替换为以下内容:

    let collectionViewCenter = CGPoint(x: cafeCollectionView.bounds.midX,
                                       y: cafeCollectionView.bounds.midY)
    

    或者,如果您想将该单元格放在左边缘,则使用一些固定x值而不是midX.

  2. 您选择注释的代码似乎也不正确。你正在做:

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

    这实际上是说“如果所选注释是我们想要的注释,则选择它。” 我认为你想要相反的,即:

    • 找到应该选择的注解;
    • 如果它没有被选中,那么就这样做。

推荐阅读