【发布时间】:2013-02-27 05:30:23
【问题描述】:
使用视图的 indexPathForItemAtPoint,我将获得一个单元格的索引路径,但绝不是 UICollectionReusableView(页眉/页脚)——因为它总是返回 nil。
【问题讨论】:
标签: ios uicollectionview uicollectionviewlayout
使用视图的 indexPathForItemAtPoint,我将获得一个单元格的索引路径,但绝不是 UICollectionReusableView(页眉/页脚)——因为它总是返回 nil。
【问题讨论】:
标签: ios uicollectionview uicollectionviewlayout
您应该制作自己的字典,将索引路径映射到标题视图。在您的 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 中:
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
}
}
}
【讨论】:
viewForSupplementaryElementOfKind 中的点击手势添加到 UICollectionReusableView 并在手势选择器中添加上述代码,您将获得所需的页眉或页脚的 indexPath。我会更新代码
您可以为 UICollectionView 添加扩展,其中传递补充视图的引用和此视图的类型(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
})
}
}
如果补充视图不可见,此方法不起作用!
【讨论】: