(Swift) UITableView - попытка переместить путь индекса к пути индекса, который не существует - PullRequest
0 голосов
/ 16 мая 2018

У меня есть UITableView, состоящий из 2 разделов. Строки изначально печатаются в разделе 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 голосов
/ 16 мая 2018

Обновление модели в вашем 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
}
...