使用视图的indexPathForItemAtPoint,我将得到一个单元格的索引路径,但永远不会得到UICollectionReusableView(页眉/页脚) - 因为它总是返回nil。
您应该创建自己的字典映射到标题视图的索引路径。在你的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
}
}