Add a simple UIView as header of UICollectionView

前端 未结 3 660
执笔经年
执笔经年 2020-12-16 09:51

I have a UICollectionView. I would like to add a header. My header would only be a UILabel. I\'ve :

1) selected \"Section Header\" as a Col

3条回答
  •  执念已碎
    2020-12-16 10:45

    In swift like below

    Register Header View

    collectionView.register(HeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerView")
    

    In UICollectionViewDataSource

    func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
    
        let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "headerView", forIndexPath: indexPath)
    
        headerView.frame.size.height = 100
    
        return headerView
    }
    

    Important is that you are supply the flow layout with the header size

    flowLayout.headerReferenceSize = CGSize(width: self.collectionView.frame.size.width, height: 100)
    

    Otherwise the data source method will not get called

提交回复
热议问题