0

I am trying to perform drag and drop inside UItableview and i am successfuly able to do that. But when i am making any update like inserting or deleting a new row. its giving me error. error is:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (10) must be equal to the number of rows contained in that section before the update (10), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

and my code is for updating the tableview is

func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {

    let destinationIndexPath: IndexPath
    if let indexPath = coordinator.destinationIndexPath{
        destinationIndexPath = indexPath
    }else{
        let section = tableView.numberOfSections - 1
        let row = tableView.numberOfRows(inSection: section)
        destinationIndexPath = IndexPath(row: row, section: section)
    }


    for item in coordinator.items {

        // IF CELL IS FROM SAME TABLEVIEW
        if let sourceIndexPath = item.sourceIndexPath{
            print("Same App")
            moveItem(at: sourceIndexPath.row, to: destinationIndexPath.row)
            DispatchQueue.main.async {
                tableView.beginUpdates()
                guard sourceIndexPath != destinationIndexPath else { return }
                tableView.deleteRows(at: [sourceIndexPath], with: .left)
                tableView.deleteRows(at: [destinationIndexPath], with: .left)
                tableView.insertRows(at: [destinationIndexPath], with: .automatic)
                tableView.endUpdates()

            }
        }
    }
}

override func tableView(_ tableView: UITableView, shouldSpringLoadRowAt indexPath: IndexPath, with context: UISpringLoadedInteractionContext) -> Bool {
    return true
}

func moveItem(at sourceIndex: Int, to destinationIndex: Int){

    guard sourceIndex != destinationIndex else { return }
    let color = colorArray[sourceIndex]
    colorArray.remove(at: sourceIndex)
    colorArray.insert(color, at: destinationIndex)
}
Ankit Baid
  • 71
  • 3
  • 8
  • 1
    You must update the model before you do any deletion or insertion of rows, in such a way that model matches the new arrangement of rows. I see two deletions and only one insertion, and I don't see _any_ deletions or insertions in your model, so there's a mismatch. – matt Feb 01 '18 at 19:43
  • Model you meant my colorArray ? – Ankit Baid Feb 01 '18 at 19:45
  • 1
    I don't know what I mean, because you don't show the data source methods. I don't know how the table is populated, because you chose to conceal that. Presumably _you_ know what the model is. I don't. – matt Feb 01 '18 at 19:47

0 Answers0