iOS; programmatically collectionView with custom headers

女生的网名这么多〃 提交于 2019-11-30 06:53:04
Wiingaard

So I figured it out, with inspiration from Mohamad Farhand.

The problem was that I had to register the subclass itself with the collectionView, instead of UICollectionReusableView.self, I used the instance of the subclass someView.. So this solved my problem:

collectionView.registerClass(SupView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader , withReuseIdentifier: "someRandonIdentifierString")

And how to initialize the view:

someView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "someRandonIdentifierString", forIndexPath: indexPath) as! SupView

Note that Swift 4.1 renames the ofKind: constant as UICollectionView.elementKindSectionHeader.

you can do it like this :

 // Setup Header
 self.collectionView?.registerClass(CollectionCustomHeader.self, forSupplementaryViewOfKind: CustomeHeaderHeader, withReuseIdentifier: "customHeader")

ALSO

 override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {

    if kind == CustomeHeaderHeader {
        let view = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "parallaxHeader", forIndexPath: indexPath)
        return view
    }

Here is a Swift 3 & 4 answer I've used in a project

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

and inside viewForSupplementaryElementOfKind

let reusableView = self.collectionView!.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "LibraryHeaderNib", for: indexPath) as! LibraryHeaderNib

return reusableView
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!