LoginSignup
24
23

More than 5 years have passed since last update.

UICollectionViewにヘッダーを付ける方法がわかった

Posted at

UICollectionViewにヘッダー、フッターを付ける方法がわからない

わかった。
ViewControllerに、「referenceSizeForHeaderInSection」を引数に取るcollectionViewメソッド(ヘッダーのサイズを返す)を設定すると表示される。

キャプチャ
(車の写真表示とか、大部分は他の方が作ったプログラムです)

【ヘッダーに関わる部分のコードだけ抜粋】

ViewController.swift
    // ヘッダーを表示する
    override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
        var header : MySupplementaryView? = nil
        if (kind == UICollectionElementKindSectionHeader) {
            header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "MyHeader", forIndexPath: indexPath)
             as? MySupplementaryView
            header?.headerLabel.text = "Car Image Gallery"
        }
        return header!
    }
    // ヘッダーのサイズを設定する
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: MyFlowLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        var size = CGSize(width: 400, height: 50)
        return size
    }

ソース

こちらにアップしました。
https://github.com/hanoopy/swift-collectionview

その他

  • 行列のある表を作ろうと思った時に、UITableViewでもできるのかと思っていたが、できないみたい。Table=行のみ、Collection=行列あり。 名前の印象と違う。
  • Storyboardを使わずにUICollectionViewを使う こちらをSwiftでやってみたが、コメントに書かれている通り実行エラーになるし、headerReferenceSizeを設定してもヘッダーは表示されない。
24
23
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
24
23