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

TableView原型单元格内嵌CollectionView:如何实现各分类项数不同?

解决TableView各Section嵌套CollectionView项数不同的问题

嗨,我来帮你搞定这个需求~首先明确说:完全不需要使用多个原型单元格,用现有的单个原型单元格就能实现,关键在于数据结构的设计和数据源的传递。

下面一步步给你讲具体怎么做:

1. 设计分层的数据源结构

你需要一个“数组包含数组”的数据结构,外层数组对应TableView的每个section,内层的每个子数组就对应该section里CollectionView要展示的所有项。比如:

// 假设你展示的是字符串数据,实际可以换成你的模型对象
var categoryData: [[String]] = [
    ["美食", "饮品", "甜点"],  // 第0个section的CollectionView有3项
    ["电子产品"],             // 第1个section的CollectionView有1项
    ["男装", "女装", "童装", "配饰"]  // 第2个section的CollectionView有4项
]

这样每个子数组的长度,就决定了对应CollectionView的项数。

2. 给TableViewCell传递对应section的数据

在你的自定义TableViewCell(就是嵌了CollectionView的那个)里,添加一个用来接收数据源的属性,比如itemData,并且在属性值变化时刷新CollectionView:

class CategoryTableViewCell: UITableViewCell, UICollectionViewDataSource {
    @IBOutlet weak var collectionView: UICollectionView!
    // 接收当前section对应的CollectionView数据源
    var itemData: [String] = [] {
        didSet {
            collectionView.reloadData()
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // 设置CollectionView的数据源为当前cell
        collectionView.dataSource = self
        // 如果是纯代码创建的CollectionView,记得注册单元格;storyboard里注册过的话可以忽略
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "ItemCell")
    }
    
    // MARK: - UICollectionViewDataSource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 直接返回数据源的长度,就是当前CollectionView的项数
        return itemData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCell", for: indexPath)
        // 这里根据你的需求配置单元格,比如添加文本标签
        let label = UILabel(frame: cell.contentView.bounds)
        label.text = itemData[indexPath.item]
        label.textAlignment = .center
        cell.contentView.addSubview(label)
        return cell
    }
}

3. 在TableView的数据源方法中赋值

回到TableView的cellForRowAt方法,给每个section对应的单元格传递对应的数据:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CategoryTableViewCell", for: indexPath) as! CategoryTableViewCell
    // 把当前section对应的子数组传给cell
    cell.itemData = categoryData[indexPath.section]
    return cell
}

这样一来,每个TableView section里的CollectionView,就会根据你传入的子数组长度展示不同数量的项,完全复用同一个原型单元格,既高效又简洁。

内容的提问来源于stack exchange,提问作者Pruthvi Hariharan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:10:31