I am implementing custom headers for UICollectionView
I need a header on the Top for Horizontal CollectionView.
I am implementing custom headers for UICollectionView
I need a header on the Top for Horizontal CollectionView.
Copyright © 2021 Jogjafile Inc.

In short, creating a custom
UICollectionViewLayoutis one way to get the results you want. This is quite a complex topic so the explanation is quite long.Before adding some code, you will need to understand the different components in a
UICollectionViewLayoutsuch as cells, supplementary views and decoration views. Check this out to know moreIn your example, above the headers are called
Supplementary viewswhich are of typeUICollectionReusableViewand the cells are, well, your cells of typeUICollectionViewCells.When assigning a layout to a collection view, the collection view makes a sequence of calls to its layout to understand how to lay the views out.
Here is an example of this I found of this:
source: https://www.raywenderlich.com/4829472-uicollectionview-custom-layout-tutorial-pinterest
In your custom layout, you must
overridethese to create the layout you desire:Setting up the layout is a bit complex, mainly because of the math involved but at the end of the day, it is just about specifying frames (x, y, width, height) for the different cells and supplementary views at for different viewports.
Custom Layout example
First I created a very basic reusable view to be used as the header above the cells in each section and this just has a label in it
Next I set up my collection view in a normal way, the only difference is I provided a custom layout class
Data source and delegate also has nothing too different but I am adding it for completeness
Finally, the most complex part, creating a custom layout class. Start by looking and understanding the instance variables we keep track of, this will change based on the layout you want to create
We then need a function to help us figure out how many items can fit in 1 column based on the cell height, spacing and available space based on the collection view height. This will help us move the cell to the next column if there is no more space in the current column:
Next, we need a function to help us find the width of a section as we need to know how long the header view should be
And as mentioned above, we need to override a few functions and properties. Let's start with
prepare()The content size property
The three layout attribute functions
And finally the invalidate layout
With all of this in place, this should give you this result:
If for some reason you weren't able to add the code to the right sections, have a look at this same example with the complete source code here
While I cannot cover everything, here are 3 great tutorials you can look at after going through this answer to understand more in depth: