Save order of UITableViewCells

社会主义新天地 提交于 2019-12-07 10:45:18

问题


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


来源:https://stackoverflow.com/questions/32321093/save-order-of-uitableviewcells

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!