如何获取UICollectionView的头部视图的索引路径?

6
使用视图的indexPathForItemAtPoint方法,可以获取单元格的索引路径,但永远不会返回UICollectionReusableView(头部/尾部视图),因为它总是返回nil。
2个回答

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
        }
    }
}

这段代码是做什么的?它是如何解决问题的? - JJJ
只需在viewForSupplementaryElementOfKind中添加轻拍手势到UICollectionReusableView,并在手势的选择器中添加上述代码,您将获得所需的标题或页脚的indexPath。我会更新代码。 - jovanpreet

1
你可以为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
        })
    }
    
}

如果补充视图不可见,则此方法无效!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接