使用视图的indexPathForItemAtPoint方法,可以获取单元格的索引路径,但永远不会返回UICollectionReusableView(头部/尾部视图),因为它总是返回nil。
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
}
}
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
}
}
}
UICollectionView.elementKindSectionHeader
或UICollectionView.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
})
}
}
如果补充视图不可见,则此方法无效!
viewForSupplementaryElementOfKind
中添加轻拍手势到UICollectionReusableView,并在手势的选择器中添加上述代码,您将获得所需的标题或页脚的indexPath。我会更新代码。 - jovanpreet