如何在 TableView 单元格上调用 SwipeToDelete 方法时立即更新 tableView 值?

How to instantly update tableView value when calling SwipeToDelete method on a TableView cell?

当我 swipeToDelete 一个单元格时,删除动画是正确的,但是单元格的索引值不会在删除时更新,直到我将 tableView 滚动到视图外并再次将其滚动回视图,仅然后单元格文本字段内的数据值会发生变化。

此外,如果我在内部添加一个 tableView.reloadData() 方法,它会正确更新单元格的值,但会扭曲删除动画(动画执行速度非常快)。我怎样才能解决这个问题?

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        try! realm.write {
            tableView.beginUpdates()
            self.realm.delete((self.selectedExercise?.wsr[indexPath.row])!)
            tableView.deleteRows(at: [indexPath], with: .automatic)
            tableView.endUpdates()
        }
    }
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = historyTableView.dequeueReusableCell(withIdentifier: "historyCell", for: indexPath)
        let wsr = selectedExercise?.wsr[indexPath.row]

        cell.textLabel?.text = "Set \(indexPath.row + 1)   \(wsr!.weight.removeZerosFromEnd()) lbs - \(wsr!.reps.removeZerosFromEnd()) Reps"
        return cell
    }

您真正需要做的就是重新加载位于要删除的单元格之外的所有单元格。所以你可以这样做:

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

    guard let selectedExercise = selectedExercise else { return }

    if editingStyle == .delete {

        var refreshIndexPaths: [IndexPath] = []
        for i in indexPath.row+1..<selectedExercise.wsr.count {
            refreshIndexPaths.append(.init(row: i, section: indexPath.section))
        }
        try! realm.write {
            self.realm.delete((self.selectedExercise.wsr[indexPath.row])!)
        }

        tableView.beginUpdates()
        tableView.deleteRows(at: [indexPath], with: .fade)
        tableView.reloadRows(at: refreshIndexPaths, with: .fade)
        tableView.endUpdates()
    }
}