I have different number of headers in a collection in my code and when I click a header each header has different actions. If I select a cell, - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
method is called. So, is there any delegate method which is called when any supplementary view is selected?
To display this section header, you'll use UICollectionReusableView . This class is like UICollectionViewCell , except it's usually used to display headers and footers. Like cells, UICollectionView places them in a reuse queue rather than deleting them when they scroll out of the visible bounds.
Use a cell registration to register cells with your collection view and configure each cell for display. You create a cell registration with your cell type and data item type as the registration's generic parameters, passing in a registration handler to configure the cell.
A view that defines the behavior for all cells and supplementary views presented by a collection view.
Here is @Geet's answer for Swift 5. There are only 9 simple steps using a delegation
// 1. create a protocol outside of your headerView class
protocol YourHeaderViewDelegate: class {
// 2. create a function that will do something when the header is tapped
func doSomething()
}
class YourHeaderView: UICollectionReusableView {
// 3. inside the headerView set a property named delegate of type YourHeaderViewDelegate? and make sure it's **weak**
weak var delegate: YourHeaderViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
// 4. add a tapGesture to your headerView
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(headerViewTapped))
addGestureRecognizer(tapGesture)
}
// 5. inside the selector method for the tapGestureRecognizer call the property and then call the doSomething method
@objc func headerViewTapped() {
delegate?.doSomething()
}
}
// 6. make sure the class with the headerView's collectionView conforms to YourHeaderViewDelegate
class ClassWithCollectionView: YourHeaderViewDelegate {
// 7. inside the class with your collectionView when you create the headerView make to set the delegate as self
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerViewId", for: indexPath) as! YourHeaderView
// 8. *** set this to self ***
headerView.delegate = self
return headerView
}
// 9. since your class conforms to the YourHeaderViewDelegate method when you tap the headerView this function will get called
func doSomething() {
print("hello!")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With