Created
April 30, 2018 12:12
-
-
Save verebes1/639ca9bb39bc987e2b7f3a245a381583 to your computer and use it in GitHub Desktop.
Using Long Press Reorder for swift reorder realm objects ID after dragging
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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