UICollectionViewのヘッダとフッタの設定
公開日:
:
Tips InterfaceBuilder, UICollectionView, Xcode
UICollectionViewで慣れないのがヘッダフッタで、毎度「どうやって設定するんだっけ…」と悩むので、備忘録を兼ねて記事を書いておこうと思います。
UITableViewと違う
NumberOf〜系統のメソッドが大体同じ感じなのでheader〜とかfooter〜とかいうメソッドがあるのかと思うと不意打ち食らうというか、これらはSupplementaryElement(サプリメント:補助的)として扱われています。
なので、[collectionView:viewForSupplementaryElementOfKind:atIndexPath:]というメソッドで対応するビューを引っ張ります。
クラスはUICollectionReuseableViewというクラスで、IBで作る場合は専用のタイトルセル(UICollectionViewCellの隣にある、Collectionの横長の棒がハイライトされているアイコン)をIBに入れて作ることができます。
IB使って実際にやるなら、派生クラスを作ってIBOutletをゴリゴリ割り当てておくと、メソッド内のデータの設定が楽になるかと思います。
- (UICollectionReusableView*)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { // セクションヘッダ・フッタを引っ張ってくる UICollectionReusableView* reusableview = nil; if (kind == UICollectionElementKindSectionHeader) { // --- ヘッダ UICollectionReusableView* headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath]; //(ここにheaderViewの中身の定義をindexPath.sectionなんかをベースに設定してやる) reusableview = headerView; } else if (kind == UICollectionElementKindSectionFooter) { // --- フッタ UICollectionReusableView* footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"FooterView" forIndexPath:indexPath]; //(ここにfooterViewの中身の定義をindexPath.sectionなんかをベースに設定してやる) reusableview = footerView; } return reusableview; }
参考サイト
関連記事
-
-
UISegmentedControlに見栄え良く背景色を設定する
UISegmentedControlをiOS7で使おうとすると、基本の背景色が「透明」になりますが、
-
-
Size ClassとUIViewController.view
タイトルの件でちょっとハマったことがある上に、特に日本語情報もStackOverflowからも情報が
-
-
AdMob組み込み覚書
書籍ではコレがかなり参考になるのでご紹介。 表題の通りで、組み込みで要注意っぽい部分だけを
-
-
User Defined Runtime Attributeについての覚書
UILabelに上下左右のパディングをつける方法を探して、結局「自分で以下のようなメソッドを持った拡
-
-
UIAlertControllerの取り扱い
旧聞ですが日本語版のStackOverflowが始動したようですね。 個人的な印象は「フィルタされ
-
-
NSAttributedStringをローカライズする方法
NSAttributedStringをLocalizeするうまい方法はないものかと探したら、これが手
-
-
UIButtonのappearanceで派生する色設定
以下のコードでUIButtonのappearanceでBackgroundColorの設定をすると、
-
-
StoryboardからPopoverを作っても位置合わせコードは必要
これだけだとわかりづらいんですが。 XcodeのStoryboardから、Segueを"Prese