LoginSignup
21
20

More than 5 years have passed since last update.

【iOS】UICollectionViewでセクションごとにヘッダを付ける

Last updated at Posted at 2015-09-19

UICollectionViewでセクションごとにヘッダを付ける

ストーリーボードの状態

ストーリーボードにはUICollectionViewが置いてある状態です。
このcollectionにセクションヘッダのnibを追加して登録していきます。
Main_storyboard.png

セクションヘッダのnibを作成する

セクションヘッダのUICollectionReusableViewを継承したMyCollectionReusableViewを作成します。

MyCollectionReusableView.swift
import UIKit
import Foundation

class MyCollectionReusableView : UICollectionReusableView {
    @IBOutlet weak var headerLabel: UILabel!
}

TopHeader.xib を作成します。
CollectionReusableViewパーツを配置します。
TopHeader_xib_—_Edit3ed.png

セクション名用のラベルを配置して、CollectionReusableViewパーツを作ったクラスと関連付けました。
TopHeader_xib_—_Edited.png

セクション名用のラベルはMyCollectionReusableViewのIBOutletと関連付けます。
TopHeader_xib_—_Edited2.png

ViewControllerのcollectionにnibを登録する

myCollectionViewはストーリーボードと関連付けているCollectionViewです。
後からグループ化しているので、0番目のセクションヘッダは表示しないようにしてみました。
セクション名のところを配列から取得するようにするとセクションごとにセクション名が出るようになります。

MyViewController.swift
    override func viewDidLoad(){

        // ヘッダーnib登録
        let nib:UINib = UINib(nibName: "TopHeader", bundle: nil)
        myCollectionView.registerNib(nib, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "MyHeader")
    }

    func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {

        var header:MyCollectionReusableView? = nil

        if (kind == UICollectionElementKindSectionHeader) {

            header = self.myCollectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "MyHeader", forIndexPath: indexPath) as? MyCollectionReusableView

            switch(indexPath.section){
                case 0:
                    return header!
                default:
                    header?.headerLabel.text = "セクション名"
                    return header!
            }
        }else{
            return header!
        }
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {

        switch(section){
            case 0:
                return CGSize(width: 0, height: 0)
            default:
                return CGSize(width: self.view.bounds.width, height: 20)
        }
    }

参考にしたサイト

[iOS6] Collection View 基本的な使い方
UICollectionViewにヘッダーを付ける方法がわかった
UICollectionViewでheaderとfooterを使う
【iOS】CollectionViewにヘッダーとフッター両方を追加する
055 UICollectionViewをセクション毎に分ける

21
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
20