I added the option in my tableview to sort/reorder cells. I used this tutorial: http://www.ioscreator.com/tutorials/reordering-rows-table-view-ios8-swift. Now I'd like to ask how I can save the sorting/order of the cells? I also use Core Data and the fetchedResultsController
.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Add an extra attribute to your Core Data model object that is used to store the sort order. For example, you could have an orderIndex
attribute:
class MyItem: NSManagedObject {
@NSManaged var myOtherAttribute: String
@NSManaged var orderIndex: Int32
}
Then, use this attribute in your sort descriptor for your fetched results controller's fetch request:
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "orderIndex", ascending: true)]
And finally, update the orderIndex
property in your UITableViewDataSource method:
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
if var items = fetchedResultsController.fetchedObjects as? [MyItem],
let itemToMove = fetchedResultsController.objectAtIndexPath(sourceIndexPath) as? MyItem {
items.removeAtIndex(sourceIndexPath.row)
items.insert(itemToMove, atIndex: destinationIndexPath.row)
for (index, item) in enumerate(items) {
item.orderIndex = Int32(index)
}
}
}