How can I set the entire header view to UICollectionView?

女生的网名这么多〃 提交于 2020-01-01 03:02:27

问题


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...


回答1:


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.



来源:https://stackoverflow.com/questions/14515975/how-can-i-set-the-entire-header-view-to-uicollectionview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!