Home > Net >  Reusable headers for UICollectionViewCompositionalLayout
Reusable headers for UICollectionViewCompositionalLayout

Time:12-31

I am trying to create descriptive headers for each section in my UICollectionViewCompositionalLayout. Something like this:

enter image description here

Here is my header:

class CafeHeaderView: UICollectionReusableView {
    
    static let reuseId = "HeaderView"
    let categoryLabel = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupContent()
    }
    
    func setupContent() {
        categoryLabel.frame = CGRect(x: 16, y: 15, width: 200, height: 17)
        categoryLabel.font = UIFont(name: "Montserratarm-Medium", size: 22)
        categoryLabel.text = "Section ?? "
        addSubview(categoryLabel)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

I registered my cell

 mainCollectionView.register(CafeHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: CafeHeaderView.reuseId)

Than created boundarySupplementaryItem

 section.boundarySupplementaryItems = [.init(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .estimated(60)), elementKind: UICollectionView.elementKindSectionHeader, alignment: .top)]

Finally

   func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
         let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: CafeHeaderView.reuseId, for: indexPath)
   
    }

So is there a way to determine the current section and set my label's text accordingly?

CodePudding user response:

Try this:


var anyArray = ["cat", "dog", "mouse", "elephant"]

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
         let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: CafeHeaderView.reuseId, for: indexPath)
   
header.yourLabel.text = anyArray[indexPath.section]

    }

To store data in your section at each cell, use indexPath.section.

  • Related