12
11

More than 5 years have passed since last update.

UICollectionView に位置固定のヘッダーを表示する

Posted at

UICollectionViewFlowLayoutsectionHeadersPinToVisibleBoundstrue にする。
同じく FlowLayout の headerReferenceSize のサイズを設定する。
ストーリーボードを使わない場合、デフォルトは (0,0) なので必ず設定する。

下記はストーリーボードを使用した場合の処理

override func viewDidLoad() {
    super.viewDidLoad()

    // あらかじめストーリーボードで CollectionView の View セクションの Tag に 1 を設定しておく
    let cv = self.view.viewWithTag(1) as! UICollectionView
    // FlowLayout を取得して sectionHeadersPinToVisibleBounds を true にする
    let fl = cv.collectionViewLayout as! UICollectionViewFlowLayout  
    fl.sectionHeadersPinToVisibleBounds = true // sectionHeadersPinToVisibleBounds は flowlayout にしかない
}

// ヘッダーのセルを生成する ヘッダーもフッターも SupplementaryElement という扱いらしい
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {

    var reusableview: UICollectionReusableView? = nil
    // ヘッダーの時のみ処理する
    if kind == UICollectionElementKindSectionHeader {
        let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "header", forIndexPath: indexPath)

        let lbl = UILabel(frame: CGRectMake(5,5,100,50))
        lbl.text = "HEADER!"
        headerView.addSubview(lbl)
        reusableview = headerView
    }
    return reusableview!
}
12
11
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
12
11