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

Swift 4中如何根据数组修改同组内UITableViewCell的背景颜色

解决UITableViewCell根据索引数组设置背景色的问题

嗨,我来帮你搞定这个问题~你当前的代码没法正确设置单元格颜色,主要有两个核心问题:

  • 类型不匹配:indexPath.row是整数类型,但你的数组里存的是字符串,直接用==对比完全不成立
  • 逻辑错误:你把整个数组和单个row值做相等判断,这不符合“检查当前row是否在目标数组中”的需求

下面是修正后的完整方案:

方案一:使用整数类型数组(推荐)

把数组改成和indexPath.row一致的整数类型,这样不用额外转换,效率更高:

// 改成整数数组,和indexPath.row类型匹配
let redCell: [Int] = [0, 1, 4]
let greenCell: [Int] = [2, 3]

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // 确保获取到可用的cell,这里根据你的需求处理nil情况,示例用guard做安全解包
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "playQuizTableViewCell") as? playQuizTableViewCell else {
        return UITableViewCell()
    }
    
    let currentRow = indexPath.row
    // 检查当前row是否在对应数组中
    if redCell.contains(currentRow) {
        cell.textLabel?.backgroundColor = .red
    } else if greenCell.contains(currentRow) {
        cell.textLabel?.backgroundColor = .green
    } else {
        cell.textLabel?.backgroundColor = .black
    }
    
    return cell
}

方案二:保留字符串数组(如果必须的话)

如果你的数组是从外部获取的字符串类型(比如服务器返回),那就把indexPath.row转换成字符串再判断:

let redCell = ["0","1","4"]
let greenCell = ["2","3"]

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "playQuizTableViewCell") as? playQuizTableViewCell else {
        return UITableViewCell()
    }
    
    let currentRowStr = String(indexPath.row)
    if redCell.contains(currentRowStr) {
        cell.textLabel?.backgroundColor = .red
    } else if greenCell.contains(currentRowStr) {
        cell.textLabel?.backgroundColor = .green
    } else {
        cell.textLabel?.backgroundColor = .black
    }
    
    return cell
}

另外要注意:每次复用cell时都要明确设置背景色,避免因为cell复用导致之前的颜色残留,上面的代码已经处理了这一点,每个分支都覆盖了颜色设置。

内容的提问来源于stack exchange,提问作者Avinash Mishra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:17:28