1

When I swipeToDelete a cell, the deletion animation is correct, but the index value of the cell does not update upon deletion until I Scroll the tableView out of view and Scroll it back into view again, only then does the Data value inside of the cell's textfield change.

Also, if I add a tableView.reloadData() method inside, it updates the cell's value correctly, but it distorts the delete animation (the animation executes super quickly). How can I fix this?

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
    }
elight
  • 562
  • 2
  • 17
  • Couple of questions... what do you mean by the index value of the cell doesn't update? What index value? Also, are you expecting the contents of other cells to update? Maybe post the contents of your `cellForRowAt` method so we have a better idea of what you're trying to accomplish. – Rob C Feb 12 '20 at 18:47
  • @Rob I updated my question and I included the cellForRowAt. I'm refering to the "indexPath.row" value. If we have 4 cells labeled [1, 2, 3, 4] and if I try to delete the second cell, the index values would not update dynamically, so it would look like this...[1, 3, 4] instead of [1, 2, 3], until I call tableview.reloadData. –  Feb 12 '20 at 18:57

1 Answers1

0

All you really have to do is reload all of the cells that lie beyond the cell you are deleting. So you can do something like this:

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()
    }
}
Rob C
  • 4,877
  • 1
  • 11
  • 24