问题
So I was reordering rows in a table, the UI end results were incorrect. Here comes the scenario:
Table content originally:
a
b
c
d
e
If I move Row 0 (currently a) to Row 4 (currently e), the end result that I am seeing is:
c
d
e
a
a
A little bit of the context:
The table is reading a list of Realm objects. I confirmed that the Realm objects are properly updated as well. If I put a tableView.reloadData() right after reordering the rows, I can get the correct UI results. However, reloading data brings in unnecessary UI animation to my app. Below is my code to perform reordering:
let realm = try! Realm()
realm.beginWrite()
let itemToMove = self.itemList?[fromIndexPath.row]
self.itemList?.remove(at: fromIndexPath.row)
self.itemList?.insert(itemToMove!, at: toIndexPath.row)
try realm.commitWrite()
I had successful experience of reordering rows in a table that was not reading Realm objects. So I am not sure if this is even related to Realm. I have researched quite a bit but not really seeing any similar issues. Any help will be greatly appreciated!
回答1:
So the tricky thing about Realm objects being the data source of a table view is that, I need to coordinate the update of Realm objects (without notifying the notification token) as well as the table view when reordering happens.
From the official Realm Swift documentation, a feature was documented to update Realm objects using commitWrite(withoutNotifying: [token]). I have struggled a bit until I found out this is a new feature released recently and my Realm version was a bit out of date. That's why when I typed in that function, Xcode was complaining. After installing Realm 2.2.0, the function showed up right away.
Below is my code for reordering rows:
do {
self.itemList?.realm?.beginWrite()
self.itemList?.move(from: fromIndexPath.row, to: toIndexPath.row)
self.tableView.moveRow(at: fromIndexPath, to: toIndexPath)
try self.itemList?.realm?.commitWrite(withoutNotifying: [self.notificationToken])
} catch let error as NSError {
fatalError(error.localizedDescription)
}
A little bit of follow-up of the question:
The background colour of odd rows in the table view were originally set to grey(just some UI feature). However, the background colour of the rows being moved will not be updated after reordering them. I tried with tableView.reloadData() and tableView.reloadRows(). But then the last row somehow ended in a weird state where it cannot be edited any more. So basically if I'd like to reorder the table again, the last row will not show up in the "edit" state/view. I am still trying to understand and to resolve this remaining issue.
来源:https://stackoverflow.com/questions/41647582/incorrect-ui-update-after-reordering-rows-in-uitableviewcontroller