Skip to content

Instantly share code, notes, and snippets.

@verebes1
Created April 30, 2018 12:12
Show Gist options
  • Save verebes1/639ca9bb39bc987e2b7f3a245a381583 to your computer and use it in GitHub Desktop.
Save verebes1/639ca9bb39bc987e2b7f3a245a381583 to your computer and use it in GitHub Desktop.
Using Long Press Reorder for swift reorder realm objects ID after dragging
extension CategoryViewController {
override func positionChanged(currentIndex: IndexPath, newIndex: IndexPath) {
// currentIndex and newIndex rows are swapped, implement accordingly
}
override func reorderFinished(initialIndex: IndexPath, finalIndex: IndexPath) {
// Gesture is finished and cell is back inside the table at finalIndex position
try! realm.write {
guard let sourceObject = categories?[initialIndex.row] else {fatalError()}
guard let destinationObject = categories?[finalIndex.row] else {fatalError()}
let destinationObjectOrder = destinationObject.id
if initialIndex.row < finalIndex.row {
for index in initialIndex.row...finalIndex.row {
let object = categories![index]
object.id -= 1
}
} else {
for index in (finalIndex.row..<initialIndex.row).reversed() {
let object = categories![index]
object.id += 1
}
}
sourceObject.id = destinationObjectOrder
tableView.reloadData()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment