6

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

4

3 回答 3

2

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

于 2013-02-27T05:49:17.003 回答
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
        }
    }
}
于 2017-02-07T10:09:02.833 回答
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
        })
    }
    
}

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

于 2020-09-22T19:11:42.607 回答