首页 > 解决方案 > UICollectionViewCells 隐藏在 headerView 后面

问题描述

将 UICollectionView 与自定义标题一起使用。奇怪的事情是隐藏在标题单元格后面的自定义单元格。下面是代码:

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

    let reusableview = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "CalendarHeaderView", for: indexPath) as! CalendarHeaderView
    
    switch kind {
    case UICollectionView.elementKindSectionHeader:
        
        reusableview.frame = CGRect(x: 0 , y: 0, width: self.view.frame.width, height: 40)
         //do other header related calls or settups
        reusableview.headerLabel.text = "Month"
        
        return reusableview
        
    default:  fatalError("Unexpected element kind")
    }
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = collectionView.bounds.width / 7.0
    let height = width
    return CGSize(width: width, height: height)
   
}

标题图片

标签: iosswiftuicollectionviewuicollectionviewcell

解决方案


func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    
    switch kind {
    case UICollectionView.elementKindSectionHeader:
        
        /// PROBLEM
        reusableview.frame = CGRect(x: 0 , y: 0, width: self.view.frame.width, height: 40)
        
        return reusableview
        
    default:  fatalError("Unexpected element kind")
    }
}

您不应该设置UICollectionView.elementKindSectionHeader. UICollectionView为您完成所有这些。您只需要告诉它需要多大 ( CGSize)。

您可以UICollectionView通过以下方法了解此尺寸 -

extension ViewController: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.bounds.width, height: 40)
    }

}

推荐阅读