(Swift)UITableView - 尝试将索引路径移动到不存在的索引路径

时间:2018-05-16 04:47:48

标签: swift uitableview indexpath

我有一个由2个部分组成的UITableView。行最初打印在第0节。它们必须可以在各部分之间移动。

当我将一个单元从第0部分移动到第1部分时,我得到:

"Attempt to move index path to index path that does not exist"

这是我的代码。

override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
    self.tableView.moveRowAtIndexPath(sourceIndexPath, toIndexPath: destinationIndexPath)
}

这些都返回正确的值:

print("source row \(sourceIndexPath.row)")
print("source section \(sourceIndexPath.section)")
print("destination row \(destinationIndexPath.row)")
print("destination section \(destinationIndexPath.section)")

关于如何解决这个问题的任何想法?

更新

我已经查看了fetchedResultsControllerDelegate,现在我有了这个:

override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {

    let movedObject = self.fetchedResultsController.objectAtIndexPath(sourceIndexPath) as! NSManagedObject
    print(movedObject)

     controller(self.fetchedResultsController, didChangeObject: movedObject, atIndexPath: sourceIndexPath, forChangeType: NSFetchedResultsChangeType.Delete, newIndexPath: destinationIndexPath)

     self.tableView.deleteRowsAtIndexPaths([sourceIndexPath], withRowAnimation: UITableViewRowAnimation.Automatic)

     controller(self.fetchedResultsController, didChangeObject: movedObject, atIndexPath: sourceIndexPath, forChangeType: NSFetchedResultsChangeType.Insert, newIndexPath: destinationIndexPath)

     self.tableView.insertRowsAtIndexPaths([destinationIndexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}

现在错误更新无效:

无效更新:第0节中的行数无效。更新后的现有部分中包含的行数(2)必须等于更新前该部分中包含的行数(2),或者减去从该部分插入或删除的行数(插入0,删除1),加上或减去移入或移出该部分的行数(0移入,0移出)。'

我正在删除然后插入,所以从技术上讲,行数应该仍然相同。

1 个答案:

答案 0 :(得分:1)

datasource 中的更新模型是将数据填充到表格中的数组然后使用moveRowAtIndexPath

override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {

            let movedObject = self.datasource[sourceIndexPath.row]
            datasource.remove(at: sourceIndexPath.row)
            datasource.insert(movedObject, at: destinationIndexPath.row)

            self.tableView.moveRowAtIndexPath(sourceIndexPath, toIndexPath: destinationIndexPath)


        }

不要忘记启用移动

override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {

    return true
}