・New File > User Interface の Empty を選択
・任意のファイル名を入力
・右上の□を○で囲ったアイコン(Library)ボタンを押下して Collection Reusable View を右側の画面にドラッグ&ドロップ
・追加後の画面
・今回のサンプルではこれにUILabelを追加したシンプルなヘッダービューを作成します。
・Libraryボタンから同じようにUILabelをReusableViewの中にドラッグ&ドロップ
・最低限のAutoLayoutを設定
・右ペインを出して以下のような感じでカスタムクラスを設定
・カスタムクラスの内容は以下
class CollectionBaseHeaderView:UICollectionReusableView{
@IBOutlet weak var headerLabel: UILabel!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
override init(frame: CGRect) {
super.init(frame: frame)
}
}
・ここまでで作成したxibファイルをStoryboardで利用する為に以下の手順を踏みます。
・Storyboard上でCollectionViewをドラッグ&ドロップ
・Libraryボタンから Collection Reusable ViewをCollectionView上にドラッグ&ドロップ
・CustomClassにxibで設定したクラスと同じクラスを設定
・CollectionViewを利用するクラスのviewDidLoadで再利用するセルの登録
override func viewDidLoad() {
super.viewDidLoad()
profileCollectionView.register(UINib(nibName: "CollectionBaseHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "CollectionBaseHeaderView")
}
・あとは通常通りにセクションの設定をしていきます。
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let testSection = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "CollectionBaseHeaderView", for: indexPath) as! CollectionBaseHeaderView
return testSection
}