I have a custom header/footer class
class CustomCollectionReusableView: UICollectionReusableView {
var pageControl: UIPageControl!
...
}
and use it in UICollectionViewDataSource appropriate method:
func collectionView(
_ collectionView: UICollectionView,
viewForSupplementaryElementOfKind kind: String,
at indexPath: IndexPath
) -> UICollectionReusableView {
if kind == customKind {
...//return CustomCollectionReusableView object
}
...
}
The problem is if I have multiple sections with the same this header/footer then how should I get callback to know in which of them user clicked on pageControl (get indexPath)?
If it was UITableViewCell/UICollectionViewCell subclass I could just call a custom delegate in it with a cell-sender param and then call for example collectionView.indexPath(for:).
The problem is there is no such method for headers/footers. There is collectionView.indexPathsForVisibleSupplementaryElements(ofKind:) only which returns multiple indexPath objects.
How to resolve this issue correctly? Should I set callback block or indexPath inside this view?
You can use protocol/delegate pattern, but Swift likes closures.
Depending on what all you need to do, you may want to take different approaches.
IF you know your collection view data structure will not change, you can capture the
sectionin a closure.For example:
Then, your
viewForSupplementaryElementOfKindmight look something like this:On the other hand, suppose you have 30 sections, and based on user-interaction or data events, you might be deleting / inserting / re-ordering sections, you don't want to rely on the captured
section.In that case, we can pass back the header view instance, and loop through the visible supplementary views to find the index path.
So our
closurechanges to:and we can do this when setting the closure:
Here's a complete example..
We'll start by defining a "section" data struct:
Where
myValwill be an index into an array of colors, which we'll use for the background of the label in a collection view cell, andnumItemswill be the number of items in the section.It will look like this when running:
Changing the current page in the section header will change the background color of the labels in that section:
SimpleCell: UICollectionViewCellclass - with a single, centered label...InteractiveHeaderView: UICollectionReusableViewclass - with a label and a page control...InteractiveHeaderViewController: UIViewControllerclass - to demonstrate...