everm1nd
everm1nd

Reputation: 731

Acting with button in UICollectionView header

I have a button called "Select" in my collection view header. How can I get section id in click-action of the button in order to iterate over cell elements in this section and mark them as selected?

Upvotes: 0

Views: 949

Answers (1)

Mendy
Mendy

Reputation: 186

You can add func indexPathForSupplementaryElement(ofKind kind: String, at point: CGPoint) -> IndexPath? method in extension of UICollectionView

extension UICollectionView {
    func indexPathForSupplementaryElement(ofKind kind: String, at point: CGPoint) -> IndexPath? {
        let targetRect = CGRect(origin: point, size: CGSize(width: 0.1, height: 0.1))
        guard let attributes = collectionViewLayout.layoutAttributesForElements(in: targetRect) else { return nil }

        return attributes.filter { $0.representedElementCategory == .supplementaryView && $0.representedElementKind == kind }.first?.indexPath
    }
}

and use this in your UIViewController for example like this

@IBAction func didSelectHeader(sender: UIView, forEvent event: UIEvent) {
        guard let point = event.allTouches?.first?.location(in: collectionView) ?? sender.superview?.convert(sender.center, to: collectionView) else { return }
        guard let indexPath = collectionView.indexPathForSupplementaryElement(ofKind: UICollectionView.elementKindSectionHeader, at: point) else { return }

        // do something with the indexPath
    }

the indexPath.item in our case is every time 0 but the indexPath.section is different, depending on the location of the header relative to the section of the collectionView

Upvotes: 1

Related Questions