Irohabook
0
3065

UICollectionViewにカスタムヘッダーをつける(referenceSizeForHeaderInSectionを使う)

UICollectionViewに(セクションヘッダーではない)ヘッダーをつけるには、referenceSizeForHeaderInSectionという引数を持つcollectionView関数を使う。

  1. カスタムヘッダーを用意する
  2. viewDidLoadでカスタムヘッダーをregisterする
  3. collectionView(viewForSupplementaryElementOfKind)
  4. collectionView(referenceSizeForHeaderInSection)

カスタムヘッダーを用意する

class HeaderView: UICollectionReusableView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.red
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

viewDidLoadでカスタムヘッダーをregisterする

collectionView.register(HeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerID")

registerという関数のうち、forSupplementaryViewOfKindという引数があるものを使う。

collectionView

2つのcollectionView関数を書く。viewForSupplementaryElementOfKindとreferenceSizeForHeaderInSectionである。

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    print(kind)
    let reusableview = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerID", for: indexPath) as! HeaderView
    reusableview.frame = CGRect(x: 0, y: 0, width: 200, height: 60)
    return reusableview
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    return CGSize(width: view.frame.width, height: 200)
}

viewForSupplementaryElementOfKindでカスタムヘッダーを返す。しかしこれだけでは表示されない。実際はreferenceSizeForHeaderInSectionでカスタムヘッダーの幅と高さを用意する。

次の記事

UICollectionView