swift - (Swift) UITableView - 尝试将索引路径移动到不存在的索引路径
问题描述
我有一个由 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 移出)。
我正在删除然后插入,所以从技术上讲,行数应该仍然相同。
解决方案
更新模型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
}
推荐阅读
- ios - 如何结合这两个功能?
- .net - 用于在 Visual Studio 2019 中调试多个项目的配置文件
- python - Python - 如何在 UDP 数据报中设置 IPv6_HOPLIMIT
- nlp - 训练 Gensim Word2vec 模型的每个句子的最小字数
- kotlin - 如何在 Kotlin 中指定 ActionListener?
- ionic-framework - 离子文件插件:copyFile“NOT_FOUND_ERR”
- r - 为什么我无法在 Shiny (R) 中显示仪表板?
- python-3.x - 从混合数据类型列中提取所有整数行
- android - Materialio Appbar 向下滚动时不隐藏
- apache-spark - 直线火花节俭服务器问题