TableView双分区侧滑删除行后移回数据出现行数异常求助
问题修复:TableView侧滑删除后数据同步异常
问题根源
你的侧滑删除逻辑存在两个致命问题:
- 先执行
self.array2.remove(at: indexPath.row)移除元素,随后又尝试访问self.array2[indexPath.row],此时该索引已无对应元素,直接触发数组越界崩溃。 - 仅更新了第二个分区的行,未同步更新第一个分区的行数,导致TableView数据源与界面显示不一致,引发行数异常。
修正后的核心代码
替换原editActionsForRowAt方法,同时优化didSelectRowAt的刷新逻辑:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // 先保存要移动的元素 let movedName = array1[indexPath.row] array2.append(movedName) array1.remove(at: indexPath.row) // 用动画更新TableView,避免直接reload的生硬感 tableView.performBatchUpdates({ // 删除第一个分区的对应行 tableView.deleteRows(at: [indexPath], with: .fade) // 插入第二个分区的最后一行 let insertIndexPath = IndexPath(row: array2.count - 1, section: 1) tableView.insertRows(at: [insertIndexPath], with: .fade) }, completion: nil) } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let deleteAction = UITableViewRowAction(style: .destructive, title: "Delete") { (_, indexPath) in // 先保存要移回的元素,避免删除后越界访问 let movedName = self.array2[indexPath.row] // 更新数据源:从array2移除,添加到array1 self.array2.remove(at: indexPath.row) self.array1.append(movedName) // 同步更新TableView的两个分区 tableView.performBatchUpdates({ // 删除第二个分区的对应行 tableView.deleteRows(at: [indexPath], with: .fade) // 插入第一个分区的最后一行 let insertIndexPath = IndexPath(row: self.array1.count - 1, section: 0) tableView.insertRows(at: [insertIndexPath], with: .fade) }, completion: nil) } return [deleteAction] }
额外优化点
- 原
cellForRowAt中第二个分区的cell初始化可以强制解包(和第一个分区保持一致),避免不必要的可选链:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! if indexPath.section == 0 { cell.textLabel?.text = array1[indexPath.row] } else { cell.textLabel?.text = array2[indexPath.row] } return cell }
- 确保你的TableViewCell identifier确实是
"cell",否则会导致解包崩溃。
内容的提问来源于stack exchange,提问作者Cristian Tamborrell
相关产品推荐
相关产品推荐

