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)
}