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

问题描述 投票:4回答:2

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

ios uicollectionview uicollectionviewlayout
2个回答
0
投票

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


1
投票
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中:

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
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.