UITableView拖放不更新tableView。获取换行错误

时间:2018-02-01 19:36:46

标签: ios swift uitableview uicollectionview swift4

我正在尝试在UItableview中执行拖放操作,并且我成功地能够做到这一点。但是当我进行任何更新时,例如插入或删除新行。它给了我错误。 错误是:

  

因未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'无效更新:第0节中的行数无效。更新后的现有部分中包含的行数(10)必须等于行数在更新(10)之前包含在该部分中,加上或减去从该部分插入或删除的行数(插入1个,删除0个)以及加入或减去移入或移出该部分的行数(0移入,0搬出去。'

我的代码用于更新tableview

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

0 个答案:

没有答案