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

Swift中无法在数组中增删TableView选中单元格的JSON ID问题

解决办法

核心问题是你当前用行索引做判断和存储,需要替换为事件ID,同时必须处理TableView的Cell复用问题,否则滑动后选中状态会出现混乱。

第一步:修改didSelectRowAt逻辑,改为操作事件ID

把原来判断、操作indexPath.row的逻辑,替换成对应事件的ID。先通过可选绑定确保能拿到有效数据,避免空值崩溃:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    guard let cell = tableView.cellForRow(at: indexPath) as? EventListCell,
          let event = eventListData?.result?.events?[indexPath.row],
          let eventId = event.id else {
        return // 拿不到有效数据直接返回,防止崩溃
    }
    
    if arrSelectedRowsBuy.contains(eventId) {
        // 已选中,移除ID并切换未选中状态
        if let index = arrSelectedRowsBuy.firstIndex(of: eventId) {
            arrSelectedRowsBuy.remove(at: index)
        }
        cell.checkImg.image = UIImage(named: "checkbox_inactive")
    } else {
        // 未选中,添加ID并切换选中状态
        arrSelectedRowsBuy.append(eventId)
        cell.checkImg.image = UIImage(named: "blue_tick")
    }
}

第二步:修复Cell复用导致的选中状态错误

原来的cellForRowAt没有根据已选中的ID设置Cell初始状态,滑动时复用的Cell会保留之前的选中状态,导致显示异常。需要在cellForRowAt里补充状态判断:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "EventListCell", for: indexPath) as! EventListCell
    
    guard let event = eventListData?.result?.events?[indexPath.row] else {
        cell.titleLbl.text = ""
        cell.checkImg.image = UIImage(named: "checkbox_inactive")
        return cell
    }
    
    cell.titleLbl.text = event.event_title
    // 根据当前事件ID是否在选中数组中,设置对应图标
    if arrSelectedRowsBuy.contains(event.id!) {
        cell.checkImg.image = UIImage(named: "blue_tick")
    } else {
        cell.checkImg.image = UIImage(named: "checkbox_inactive")
    }
    return cell
}

关键注意事项

  • 强制解包要谨慎:eventListData、events、event.id都是可选类型,用guard let做可选绑定,确保拿到有效数据再执行后续操作,避免崩溃。
  • 必须处理Cell复用:这是新手常忽略的点,不处理的话滑动TableView时,选中状态会出现错乱,一定要在cellForRowAt中根据选中数组重置Cell状态。

内容的提问来源于stack exchange,提问作者swift doubts

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 06:42:49