swift collectionview的header

1.新建一个基于UICollectionReusableView 的headView

2.在viewDidLoad(中注册

带xib的注册方式 ,但是不知道为什么会报错

homeCollectionView.register(UINib.init(nibName: "HomeCollectionReusableView", bundle: nil), forSupplementaryViewOfKind: "UICollectionElementKindSectionHeader", withReuseIdentifier: "header")

当改成不带xib的注册时,设置成功了

homeCollectionView.register(HomeCollectionReusableView.self, forSupplementaryViewOfKind: "UICollectionElementKindSectionHeader", withReuseIdentifier: "header")

3.设置header的高度

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

    return CGSize.init(width: kWidth, height: 20)

}

4.设置header的内容

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

    var reusableview:UICollectionReusableView!

    if kind == UICollectionElementKindSectionHeader{

        reusableview = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath) as! HomeCollectionReusableView

          reusableview.backgroundColor = Helper().stringToColor(str: "#F5F5F5")

   }

    return reusableview

}

你可能感兴趣的:(swift collectionview的header)