Created
July 27, 2016 04:51
-
-
Save kishikawakatsumi/cc4a1f32fb8ee34eb509d54027d731b5 to your computer and use it in GitHub Desktop.
Reorder Realm Results in UITableView
This file contains hidden or 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
| import UIKit | |
| import RealmSwift | |
| class Data: Object { | |
| dynamic var name = "" | |
| ... | |
| dynamic var order = 0 // ไธฆในๆฟใใฎใใใฎใซใฉใ ใๅฟ ่ฆ | |
| } | |
| class ViewController: UITableViewController { | |
| lazy var realm = try! Realm() | |
| var objects: Results<Data>! | |
| override func viewDidLoad() { | |
| super.viewDidLoad() | |
| objects = realm.objects(Data.self).sorted("order") | |
| } | |
| override func numberOfSectionsInTableView(tableView: UITableView) -> Int { | |
| return 1 | |
| } | |
| override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
| return objects.count | |
| } | |
| override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { | |
| let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) | |
| ... | |
| return cell | |
| } | |
| override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { | |
| try! realm.write { | |
| let sourceObject = objects[sourceIndexPath.row] | |
| let destinationObject = objects[destinationIndexPath.row] | |
| let destinationObjectOrder = destinationObject.order | |
| if sourceIndexPath.row < destinationIndexPath.row { | |
| // ไธใใไธใซ็งปๅใใๅ ดๅใ้ใฎ้ ็ฎใไธใซใทใใ | |
| for index in sourceIndexPath.row...destinationIndexPath.row { | |
| let object = objects[index] | |
| object.order -= 1 | |
| } | |
| } else { | |
| // ไธใใไธใซ็งปๅใใๅ ดๅใ้ใฎ้ ็ฎใไธใซใทใใ | |
| for index in (destinationIndexPath.row..<sourceIndexPath.row).reverse() { | |
| let object = objects[index] | |
| object.order += 1 | |
| } | |
| } | |
| ใใใใใใใใ | |
| ใใใใใใใใ// ็งปๅใใใปใซใฎไธฆใณใ็งปๅๅ ใซๆดๆฐ | |
| sourceObject.order = destinationObjectOrder | |
| } | |
| } | |
| override func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool { | |
| return false | |
| } | |
| override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { | |
| return true | |
| } | |
| override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { | |
| return .None | |
| } | |
| } |
Thank you. Helped a lot
THANK YOU!!
Thank you ๐
This is genius, thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks Alot!!!