UICollectionView表头仅显示数组最后元素求助:如何为各表头设数组文本
解决UICollectionView分组表头仅显示最后一个元素的问题
我一眼就看出问题出在哪了——那个多余的循环就是罪魁祸首!
你得明白,UICollectionView会为每个分组单独调用viewForSupplementaryElementOfKind方法来生成对应的表头,结果你在方法里加了个循环,把同一个表头的sectionHeader.text反复赋值,最后自然只会留下循环最后一次的内容。而且你用indexPath[i]的写法也是错误的,获取当前分组的索引应该用indexPath.section才对。
直接把代码改成这样就能解决问题:
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let sectionHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderIdentifier", for: indexPath) as! SectionHeaderReusableView // 直接根据当前分组索引取对应标题,无需循环 sectionHeaderView.sectionHeader.text = sectionNames[indexPath.section] return sectionHeaderView }
另外还要注意一个关键细节:确保UICollectionView的分组数量和sectionNames数组的元素数量一致,不然会触发数组越界崩溃。记得在numberOfSections方法里返回数组的长度:
func numberOfSections(in collectionView: UICollectionView) -> Int { return sectionNames.count }
这样每个分组的表头就能正确显示对应数组里的内容啦!
内容的提问来源于stack exchange,提问作者Smitesh Wadher
相关产品推荐
相关产品推荐

