【问题标题】:How to get the index path of a UICollectionView header?如何获取 UICollectionView 标头的索引路径?
【发布时间】:2013-02-27 05:30:23
【问题描述】:

使用视图的 indexPathForItemAtPoint,我将获得一个单元格的索引路径,但绝不是 UICollectionReusableView(页眉/页脚)——因为它总是返回 nil。

【问题讨论】:

    标签: ios uicollectionview uicollectionviewlayout


    【解决方案1】:

    您应该制作自己的字典,将索引路径映射到标题视图。在您的 collectionView:viewForSupplementaryElementOfKind:atIndexPath: 方法中,将视图放入字典中,然后再返回。在您的 collectionView:didEndDisplayingSupplementaryView:forElementOfKind:atIndexPath: 中,从字典中删除视图。

    【讨论】:

    【解决方案2】:
    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        switch kind {
        case UICollectionElementKindSectionHeader:
            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath) as! HeaderCollectionReusableView
            let gestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didSelectSection(gesture:)))
            headerView.addGestureRecognizer(gestureRecognizer)
            return headerView
        }
    }
    

    现在在 didSelectSection 中:

    func didSelectSection(gesture: UITapGestureRecognizer) {
        let indexPaths = self.collectionView?.indexPathsForVisibleSupplementaryElements(ofKind: UICollectionElementKindSectionHeader)
        for indexPath in indexPaths! {
            if (gesture.view as! HeaderCollectionReusableView) == collectionView?.supplementaryView(forElementKind: UICollectionElementKindSectionHeader, at: indexPath){
                print("found at : \(indexPath)")
                break
            }
        }
    }
    

    【讨论】:

    • 这段代码有什么作用?它是如何解决问题的?
    • 只需将viewForSupplementaryElementOfKind 中的点击手势添加到 UICollectionReusableView 并在手势选择器中添加上述代码,您将获得所需的页眉或页脚的 indexPath。我会更新代码
    【解决方案3】:

    您可以为 UICollectionView 添加扩展,其中传递补充视图的引用和此视图的类型(UICollectionView.elementKindSectionHeaderUICollectionView.elementKindSectionFooter

    extension UICollectionView {
        
        func indexPathForSupplementaryElement(_ supplementaryView: UICollectionReusableView, ofKind kind: String) -> IndexPath? {
            let visibleIndexPaths = self.indexPathsForVisibleSupplementaryElements(ofKind: kind)
            return visibleIndexPaths.first(where: {
                self.supplementaryView(forElementKind: kind, at: $0) == supplementaryView
            })
        }
        
    }
    

    如果补充视图不可见,此方法不起作用!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-09
      • 1970-01-01
      • 2011-03-26
      相关资源
      最近更新 更多