UICollectionViewでheaderとfooterを使う

誤って10年近く使っていたサーバーを吹っ飛ばしてしまいログが消滅しました。
技術ブログは、はてな使ってて助かりました。


storyboardからheader / footerを追加する

さて、UICollectionViewでheader / footerを追加する方法について。
UITableViewでは、適当にViewでも引っ張って来てやれば追加できたりしますが
UICollectionViewの場合は、「Collection Reusable View」を使います。

これをCollectionViewに引っ張って行ってやればheader Viewは追加できますが
footer Viewは追加できません。では、どうするかと言うと

CollectionViewを選択して、AccessoriesからSection Footerにチェックを入れてやります。
そうすると自動的にfooter用のReusable Viewがセットされるはずです。


コードからheader / footerをカスタマイズする

header / footerそれぞれのReusable Viewのidentifierを設定した上で

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView 
 viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath

この関数内のkindでUICollectionElementKindSectionHeader / Footerを判別して処理を書きます。
詳しくは、参考にした以下のサイトで解説されています。


kind (NSString* )の比較は、isEqualToStringでやった方がいいと思う。


◆【iOS】CollectionViewにヘッダーとフッター両方を追加する
http://qiita.com/kaktaam/items/6035708823f31d4530a1

◆ How to Add Header and Footer View in UICollectionView
http://www.appcoda.com/supplementary-view-uicollectionview-flow-layout/