Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the entire header view to UICollectionView?

I want to set the header to collection view, just like UITableViewController's setTableHeader does.

I found the way to set the each section's header on collection view, but I couldn't find how to set the header view of the entire header.

Apple's reference of UICollectionViewLayout says "Supplementary views present data but are different than cells. Unlike cells, supplementary views cannot be selected by the user. Instead, you use supplementary views to implement things like header and footer views for a given section or for the entire collection view. Supplementary views are optional and their use and placement is defined by the layout object.", but I don't know how to implement header view for the entire collection view.

I tried to implement this by making a section header view rectangle only to the first section, but it was different with tableHeader's that.

In table view, if I set the content offset to below header, the content size automatically expands so that the header is hidden although there exist a few elements.

But in collection view, modifying content offset only works fine when there exist many elements enough to make a scroll.

I tried to dynamically expand content size when there exist a few elements, but it seems that it doesn't work fine...

like image 413
glast Avatar asked Jan 25 '13 05:01

glast


1 Answers

I implemented this using a custom layout and repositioning the header on every scroll event. Start with subclassing UICollectionViewLayout, there are tons of tutorial on the web, this is a good one: http://markpospesel.wordpress.com/2012/10/25/fixing-circlelayout/

Then the trick is to always return YES to shouldInvalidateLayoutForBoundsChange:, and in prepareLayout reposition (ie. change the layoutAttributes' frame) the header based on the collection view xOffset and yOffset.

Use a supplementary view with NSIndexPath 0-0.

layoutAttributesForElementsInRect: will be called on every frame, so if you have a lot of items in your collection view, you will need to cache the result so it does not impact performance. All attributes should be untouched except for that one header.

Source: I spent 1 month working on this particular topic.

like image 113
Fabien Warniez Avatar answered Nov 15 '22 16:11

Fabien Warniez