可重用 headers 用于 UICollectionViewCompositionalLayout

Reusable headers for UICollectionViewCompositionalLayout

我正在尝试为我的 UICollectionViewCompositionalLayout 中的每个部分创建描述性 header。像这样:

这是我的 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")
    }
}

我注册了我的手机

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

比创建的 boundarySupplementaryItem

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

终于

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

那么有没有办法确定当前部分并相应地设置我的标签文本?

试试这个:

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]
return header
    }

要在每个单元格的部分中存储数据,请使用 indexPath.section