同一ViewController下第二个UICollectionView无法显示问题求助
修复方案
问题根因
- 未给两个UICollectionView设置
delegate和dataSource,未关联代理的CollectionView不会触发数据源方法,无法渲染内容 cellForItemAt方法逻辑冗余,无论处理哪一个CollectionView都会先出队产品类Cell,造成不必要的性能消耗- 额外排查项:确认两个UICollectionView的约束配置正常,不存在宽高为0、位置重叠、超出屏幕显示区域的问题
修正代码
HomeViewController.swift
import UIKit class HomeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource{ @IBOutlet weak var productCollectionView: UICollectionView! @IBOutlet weak var storesCollectionView: UICollectionView! var productsImages:[String] = ["pillImage", "pillyImage", "pillsImage"] var storesImages:[String] = ["compstoreImage", "compeImage", "compeStore"] override func viewDidLoad() { super.viewDidLoad() // 为两个CollectionView绑定代理和数据源 productCollectionView.delegate = self productCollectionView.dataSource = self storesCollectionView.delegate = self storesCollectionView.dataSource = self } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView == storesCollectionView { return storesImages.count } return productsImages.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 按CollectionView类型分支处理Cell逻辑 if collectionView == storesCollectionView { let cell = storesCollectionView.dequeueReusableCell(withReuseIdentifier: "storesCell", for: indexPath) as! StoreCollectionViewCell cell.compstoreImage.image = UIImage(named: storesImages[indexPath.row]) return cell } else { let cell = productCollectionView.dequeueReusableCell(withReuseIdentifier: "productsCell", for: indexPath) as! productCollectionViewCell cell.pillImage.image = UIImage(named: productsImages[indexPath.row]) return cell } } }
其他文件
StoreCollectionViewCell.swift、productCollectionViewCell.swift代码无需调整。
注意事项
- 确认两个Cell的复用ID和Storyboard/Xib中设置的完全一致
- 确认Assets中的图片名称和代码中写的完全匹配,iOS资源名称大小写敏感
内容的提问来源于stack exchange,提问作者Maaz Adil
相关产品推荐
相关产品推荐

