Save order of UITableViewCells

帅比萌擦擦* 提交于 2019-12-05 12:52:11

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