[swift] CollectionViewにReusableviewを使用してフッター・ヘッダーを追加
目次
CollectionViewにReusableviewを使用してフッター・ヘッダーを追加
StoryBoard
StoryBoardにCollectionViewを配置して、Reusableviewをフッター・ヘッダー位置に配置。
それぞれのReusableviewのIdentifierを「HeaderSection」「FooterSection」と指定
*Identifierの名前は任意
サンプルコード
//セクションの個数を返すメソッド
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
//セクションを返すメソッド
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView
{
if (kind == "UICollectionElementKindSectionHeader") {
//ヘッダーの場合
let testSection = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderSection", forIndexPath: indexPath) as! TestCollectionReusableView
//ヘッダーの背景色は紫、ラベルにセクション名を設定する。
testSection.backgroundColor = UIColor(red: 0.7, green: 0.7,blue: 0.8, alpha: 1.0)
testSection.testLabel.text = sectionIndex[indexPath.section]
return testSection
} else {
//フッターの場合
let testSection = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionFooter, withReuseIdentifier: "FooterSection", forIndexPath: indexPath)
//フッターの背景色を変更
testSection.backgroundColor = UIColor(red: 0.5, green: 0.6,blue: 0.5, alpha: 1.0)
return testSection
}
}