6

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.

akaru
  • 6,299
  • 9
  • 63
  • 102

2 Answers2

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 :

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
        }
    }
}
jovanpreet
  • 103
  • 12
  • What does this code do? How does it solve the problem? – JJJ Feb 07 '17 at 10:27
  • just add tap gesture in `viewForSupplementaryElementOfKind` to UICollectionReusableView and in the selector of gesture add the above code u will get indexPath of the header or footer as you want. I will update the code – jovanpreet Feb 07 '17 at 11:13
1

You can add extension for UICollectionView where pass reference of supplementary view and kind of this view (UICollectionView.elementKindSectionHeader or 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
        })
    }
    
}

This method doesn't work if supplementary view isn't visible!