Swift中如何为UITableView单元格循环设置四种不同背景色
UITableView Cell 循环配色实现方案
实现逻辑
通过行号对颜色总数取模的方式实现循环配色,完全匹配需求:
- 提前按顺序定义颜色数组:
[粉色, 黄色, 绿色, 蓝色] - 用当前cell的行号
indexPath.row对4取余,得到颜色数组的下标 - 取出对应下标颜色赋值即可,自动循环适配任意行数的配色需求
具体代码修改
- 在当前视图控制器类中定义全局颜色数组:
// 数组内可替换为你自己的自定义RGB颜色 private let cellBgColors: [UIColor] = [.systemPink, .systemYellow, .systemGreen, .systemBlue]
- 修改
cellForRowAt方法中的背景色赋值逻辑,完整代码如下:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "HomePostsTableViewCell", for: indexPath) as! HomePostsTableViewCell cell.selectionStyle = .none // 核心配色逻辑 let colorIndex = indexPath.row % cellBgColors.count cell.catView.backgroundColor = cellBgColors[colorIndex] cell.categoryLabel.text = category return cell }
效果验证
- 2个cell时:第0行取索引0(粉色)、第1行取索引1(黄色),符合要求
- 4个cell时:依次取索引0-3,对应四个颜色,符合要求
- 8个cell时:第4行取4%4=0(粉色)、第5行取5%4=1(黄色),以此类推循环,符合要求
内容的提问来源于stack exchange,提问作者SwiftABC
相关产品推荐
相关产品推荐

