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

时间:2013-02-27 05:30:23

标签: ios uicollectionview uicollectionviewlayout

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

3 个答案:

答案 0 :(得分: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
    }
}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您可以为UICollectionView添加扩展名,并在其中传递补充视图的引用以及该视图的种类(loaded_images.append(lr_img_data) import os from os import listdir from matplotlib import image, pyplot imgDir = 'UFO-120/train_val/lrd/' loaded_images = list() for filename in listdir(imgDir): # load image lr_train_data = image.imread(imgDir+filename, format='JPG') # store loaded image loaded_images.append(lr_train_data) print('> loaded %s %s' % (imgDir+filename, lr_train_data.shape))

UICollectionView.elementKindSectionHeader

如果看不到补充视图,此方法将不起作用!