UICollectionView分区数量未按数组计数正常显示问题排查
问题分析与修复方案
我来帮你排查下这个问题,你的代码里有几个关键的逻辑漏洞导致了“单个数组有数据却不显示分区”的现象:
1. numberOfSections 可选值判断逻辑错误
你在判断数组是否为空时,直接使用了 self.recentSearchValue?.count == 0 这类写法。如果数组是 nil,nil == 0 在Swift中会被判定为 false,导致符合条件的分支无法触发。比如当 pastConsultationList 有数据但 recentSearchValue 是 nil 时,第三个 else if 条件会因为后半部分不成立而跳过,最终走到 else 返回0个分区。
2. numberOfItemsInSection 分区对应关系错误
当只有一个分区时,你没有区分这个分区对应的是哪个数组。比如仅 pastConsultationList 有数据时,numberOfSections 返回1,但 numberOfItemsInSection 中section0返回的是 recentSearchValue 的计数(0),导致分区内没有可显示的item,看起来就像分区不存在。
3. 分区头部标题设置逻辑不严谨
同样,单分区场景下没有判断对应的数组类型,可能导致头部标题无法正确显示。
修复后的完整代码
修正分区数量计算
func numberOfSections(in collectionView: UICollectionView) -> Int { if collectionView == specialityCollection { return 1 } else if collectionView == recentSearchCollection { // 先统一处理可选值,转成确定的计数 let recentCount = self.recentSearchValue?.count ?? 0 let pastCount = self.pastConsultationList?.count ?? 0 if recentCount > 0 && pastCount > 0 { return 2 } else if recentCount > 0 || pastCount > 0 { return 1 } else { return 0 } } else { return 0 } }
修正分区内item数量计算
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView == specialityCollection { return self.SpecialtyList?.count ?? 0 } else { let recentCount = self.recentSearchValue?.count ?? 0 let pastCount = self.pastConsultationList?.count ?? 0 // 处理单分区场景 if recentCount > 0 && pastCount == 0 { return recentCount } else if pastCount > 0 && recentCount == 0 { return pastCount } // 处理双分区场景 switch section { case 0: return recentCount case 1: return pastCount default: return 0 } } }
修正分区头部标题设置
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { guard let sectionHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderView", for: indexPath) as? HeaderView else { return UICollectionReusableView() } let recentCount = self.recentSearchValue?.count ?? 0 let pastCount = self.pastConsultationList?.count ?? 0 // 根据当前数据状态设置对应标题 if recentCount > 0 && pastCount > 0 { sectionHeaderView.headerTitle.text = self.headerTitle[indexPath.section] } else if recentCount > 0 { sectionHeaderView.headerTitle.text = self.headerTitle[0] } else if pastCount > 0 { sectionHeaderView.headerTitle.text = self.headerTitle[1] } return sectionHeaderView }
注意:请确保
headerTitle数组至少包含2个元素,避免数组越界问题。
内容的提问来源于stack exchange,提问作者Shubhangi Singh
相关产品推荐
相关产品推荐

