How to get the index path of a UICollectionView header?

♀尐吖头ヾ 提交于 2019-12-23 12:28:25

问题


Using the view's indexPathForItemAtPoint, I will get an index path for a cell, but never a UICollectionReusableView (header/footer) -- as it always returns nil.


回答1:


You should make your own dictionary mapping index paths to header views. In your collectionView:viewForSupplementaryElementOfKind:atIndexPath: method, put the view into the dictionary before returning it. In your collectionView:didEndDisplayingSupplementaryView:forElementOfKind:atIndexPath:, remove the view from the dictionary.




回答2:


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

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


来源:https://stackoverflow.com/questions/15104862/how-to-get-the-index-path-of-a-uicollectionview-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!