Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kishikawakatsumi/543f961f3f70c080218db07850737852 to your computer and use it in GitHub Desktop.
Save kishikawakatsumi/543f961f3f70c080218db07850737852 to your computer and use it in GitHub Desktop.
Reorder Realm List in UITableView
import UIKit
import RealmSwift
class Data: Object {
dynamic var name = ""
...
}
class DataWrapper: Object {
let list = List<Data>()
}
class ViewController: UITableViewController {
lazy var realm = try! Realm()
var objects: List<Data>!
override func viewDidLoad() {
super.viewDidLoad()
...
objects = realm.objects(DataWrapper.self).first?.list
}
// MARK: - Table View
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)
let object = objects[indexPath.row]
cell.textLabel!.text = object.num.description
return cell
}
override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
try! realm.write {
let sourceObject = objects[sourceIndexPath.row]
objects.removeAtIndex(sourceIndexPath.row)
objects.insert(sourceObject, atIndex: destinationIndexPath.row)
}
}
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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment