如何获得UICollectionView标头的索引path?

使用视图的indexPathForItemAtPoint,我将得到一个单元格的索引path,但从来没有一个UICollectionReusableView(header / footer) – 因为它总是返回nil。

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

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