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

如何通过代码设置UICollectionView中两类自定义单元格的显示数量

实现CollectionView混合显示指定数量的自定义单元格

嘿,这个需求其实很好实现,咱们分几步来搞定:

1. 先准备一个数据源标记数组

首先,我们需要一个数组来明确每个位置该显示哪种单元格——毕竟你要7个PhotoCell和4个ArticleCell,直接把这个规则写进数组里最直观:

// 和你注册时用的复用标识符保持一致
let picCell = "PhotoCell"
let articleCell = "ArticleCell"

// 构造标记数组:7个PhotoCell标记 + 4个ArticleCell标记
private let cellTypes: [String] = Array(repeating: picCell, count: 7) + Array(repeating: articleCell, count: 4)

2. 返回正确的单元格总数

在CollectionView的数据源方法numberOfItemsInSection里,直接返回标记数组的长度,这样就确保总共显示11个单元格:

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return cellTypes.count
}

3. 根据标记返回对应单元格

接下来在cellForItemAt方法里,根据当前位置的标记,取出对应的复用标识符,获取并配置单元格:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cellType = cellTypes[indexPath.item]
    
    if cellType == picCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: picCell, for: indexPath) as! PhotoCell
        // 这里添加PhotoCell的配置逻辑,比如设置图片、文字等
        return cell
    } else {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: articleCell, for: indexPath) as! ArticleCell
        // 这里添加ArticleCell的配置逻辑
        return cell
    }
}

额外小提示

如果后续需要调整两种单元格的数量,只需要修改cellTypes数组里的count参数就行,非常灵活。另外,你已经完成了单元格的注册,这部分完全没问题~

内容的提问来源于stack exchange,提问作者Prentice Lathon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:03:41