【问题标题】:Reusable headers for UICollectionViewCompositionalLayoutUICollectionViewCompositionalLayout 的可重用标头
【发布时间】:2021-12-31 07:34:49
【问题描述】:

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

这是我的标题:

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)
   
    }

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

【问题讨论】:

    标签: swift uitableview uicollectionview uicollectionviewlayout uicollectionreusableview


    【解决方案1】:

    试试这个:

    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

    【讨论】:

    • 谢谢,成功了))
    猜你喜欢
    • 2022-07-15
    • 2023-03-18
    • 1970-01-01
    • 2020-12-05
    • 2021-11-28
    • 2021-06-25
    • 2021-12-10
    • 2020-06-29
    • 2022-10-26
    相关资源
    最近更新 更多