Programmatically create UICollectionView with custom headers

后端 未结 4 1216
予麋鹿
予麋鹿 2020-12-29 22:39

I\'m making an iOS app in swift, and I\'m trying to make a collectionView programmatically. I want to use my own subclass of UICollectionReusableView as a header for the Col

相关标签:
4条回答
  • 2020-12-29 23:03

    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
    }
    
    0 讨论(0)
  • 2020-12-29 23:05

    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
    
    0 讨论(0)
  • 2020-12-29 23:05

    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
    
    0 讨论(0)
  • 2020-12-29 23:09

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

    0 讨论(0)
提交回复
热议问题