Save order of UITableViewCells

2019-05-07 07:55发布

问题:

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)
            }
    }
}