Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reorder Realm Results in UITableView
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
}
}
@tenhow

This comment has been minimized.

Copy link

@tenhow tenhow commented Jun 17, 2017

thanks a lot

@tenhow

This comment has been minimized.

Copy link

@tenhow tenhow commented Jun 17, 2017

wonderful solution, very usefull !it solves my fuzzy of ordering the realm objects

@tenhow

This comment has been minimized.

Copy link

@tenhow tenhow commented Jun 17, 2017

Some Problem!,I have set
class MyObject: Object {
dynamic var order = 0
}
usage:
let results = try! Realm().objects(MyObject.self).sorted(byKeyPath: "order")

but when it goes to delete cell, its funny, whenever which cell I delete, the animation always delete the last one

@tenhow

This comment has been minimized.

Copy link

@tenhow tenhow commented Jun 17, 2017

finally I found that ,after any deletion, the rows will go to mass, I guess my order init is not correct, how about your order init?

@tenhow

This comment has been minimized.

Copy link

@tenhow tenhow commented Jun 17, 2017

And for initialization, I have capsuled a save method to set order, by the way

func save()  {

let realm = try! Realm()
realm.beginWrite()
self.order = APRealm().objects(self.classForCoder as! Object.Type).count
realm.add(self)
try! realm.commitWrite()

}

@Heki2017

This comment has been minimized.

Copy link

@Heki2017 Heki2017 commented Mar 2, 2018

thanks very much

@rodydavis

This comment has been minimized.

Copy link

@rodydavis rodydavis commented Apr 6, 2018

Swift 4.1:

`override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
try! realm?.write {
let sourceObject = items[sourceIndexPath.row]
let destinationObject = items[destinationIndexPath.row]

        let destinationObjectOrder = destinationObject.order
        
        if sourceIndexPath.row < destinationIndexPath.row {
            
            for index in sourceIndexPath.row...destinationIndexPath.row {
                let object = items[index]
                object.order -= 1
            }
        } else {
            
            for index in (destinationIndexPath.row..<sourceIndexPath.row).reversed() {
                let object = items[index]
                object.order += 1
            }
        }
        sourceObject.order = destinationObjectOrder
    }
}`
@Ksen17

This comment has been minimized.

Copy link

@Ksen17 Ksen17 commented Dec 28, 2018

Thank you
really helpful

@StuffbyYuki

This comment has been minimized.

Copy link

@StuffbyYuki StuffbyYuki commented Apr 16, 2019

Thank you. Solved a problem in my code.

@jimmychung28

This comment has been minimized.

Copy link

@jimmychung28 jimmychung28 commented May 9, 2019

Thanks Alot!!!

@MattMash

This comment has been minimized.

Copy link

@MattMash MattMash commented Jul 31, 2019

Thank you. Helped a lot

@KEBRN

This comment has been minimized.

Copy link

@KEBRN KEBRN commented Nov 17, 2019

THANK YOU!!

@sunshineLixun

This comment has been minimized.

Copy link

@sunshineLixun sunshineLixun commented Dec 7, 2019

Thank you 🎉

@genefever

This comment has been minimized.

Copy link

@genefever genefever commented Jul 11, 2020

This is genius, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment