Перемещение ячеек в новый раздел с помощью UITableViewDiffableDataSource приводит к сбою приложения при установке для animatingDifferences значения true
Итак, я пытаюсь научиться использовать
UITableViewDiffableDataSource
и возникли проблемы с перемещением ячеек в разные секции. Прямо сейчас я просто сосредотачиваюсь на вставке ячеек в раздел друзей. Проблема в том, что приложение вылетает на
.apply(snapshot, animatingDifferences: animatingDifferences)
когда
animatingDifferences
установлено значение true. Когда для него установлено значение false, сбой не происходит, но это не дает пользователю приятного эффекта при вставке ячеек в новый раздел, это дает «мгновенный» эффект, к которому я бы предпочел не прибегать.
Я получаю вот такую ошибку:
«Недопустимое обновление: недопустимое количество строк в разделе 0. Количество строк, содержащихся в существующем разделе после обновления (4), должно быть равно количеству строк, содержащихся в этом разделе до обновления (4), плюс или минус количество строк, вставленных или удаленных из этого раздела (0 вставлено, 0 удалено) и плюс или минус количество строк, перемещенных в этот раздел или из него (1 перемещено, 0 перемещено) ».
Я смотрю на количество строк в разделе после обновления, и оно возвращает правильное новое значение, но все равно дает сбой?
Прямо сейчас мой DiffableDataSource следующий:
/* Used to edit are cells but also configures are cell on first launch */
private lazy var tableViewDataSource: EditEnabledDiffableDataSource = {
let dataSource = EditEnabledDiffableDataSource(tableView: tableView) { [weak self] tableView, _, contact in
guard let detailTableViewCell = tableView.dequeueReusableCell(withIdentifier: String(describing: DetailTableViewCell.self)) as? DetailTableViewCell else {
return UITableViewCell()
}
if let userInfo = self?.friendsContacts.first(where: { $0.id == contact.id }) {
detailTableViewCell.configure(with: userInfo)
}
if let userInfo = self?.allContacts.first(where: { $0.id == contact.id }) {
detailTableViewCell.configure(with: userInfo)
}
return detailTableViewCell
}
//Updates are arrays
dataSource.deleteClosure = { contactID in
self.allContacts.removeAll(where: { $0.id == contactID.id})
self.friendsContacts.removeAll(where: { $0.id == contactID.id})
}
dataSource.updateClosure = { contactID, index in
var snap = dataSource.snapshot()
self.friendsContacts.insert(contactID, at: index.row)
self.configureInitialSnapshot(animatingDifferences: true)
}
return dataSource
}()
Тогда внутри моего
EditEnabledDiffableDataSource
У меня есть это:
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
super.tableView(tableView, moveRowAt: sourceIndexPath, to: destinationIndexPath)
var snapshot = snapshot()
if let sourceId = itemIdentifier(for: sourceIndexPath) {
if let destinationId = itemIdentifier(for: destinationIndexPath) {
guard sourceId != destinationId else {
return // destination is same as source, no move.
}
// valid source and destination
if sourceIndexPath.row > destinationIndexPath.row {
snapshot.moveItem(sourceId, beforeItem: destinationId)
} else {
snapshot.moveItem(sourceId, afterItem: destinationId)
}
} else {
// no valid destination, eg. moving to the last row of a section
snapshot.deleteItems([sourceId])
snapshot.appendItems([sourceId], toSection: snapshot.sectionIdentifiers[destinationIndexPath.section])
}
deleteClosure?(sourceId)
updateClosure?(sourceId, destinationIndexPath)
}
}