UICollectionView with two headers

cannyboy picture cannyboy · Aug 9, 2013 · Viewed 13.8k times · Source

Having two headers in UICollectionView?

I've got a UICollectionView which uses the flow layout, which also has a header and footer:

---------   
| head  |
---------
| A | B |
---------
| C | D |
---------
| foot  |
---------

Occasionally, I'd like to have two headers, like so:

---------   
| head1 |
---------   
| head2 |
---------
| A | B |
---------
| C | D |
---------
| foot  |
---------

I'm stuck on how to achieve this. The flow layout only appears to allow one head and one foot. How can I add a second header?


edit: I have also implemented sticky headers - http://blog.radi.ws/post/32905838158/sticky-headers-for-uicollectionview-using - but I only want the first header to be sticky. This is why I can't just include everything in one header.

Answer

Warewolf picture Warewolf · Aug 13, 2013

You just need to use a simple trick.Show header and footer both for all sections.

In which section you do not want to show footer just pass its size zero as :--

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    if(section==0)
    {
        return CGSizeZero;
    }

    return CGSizeMake(320, 50);
}

Here I have used two sections like

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

And passed no of rows in only one sections that is the last one as

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section==1) {
        return 20;
    }
    return 0;
}

And here is my output ---

enter image description here

Red View is header and Green One is footer.

Here u can get the entire Implementation File