You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

同一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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 07:45:07