保存UITableViewCells的顺序 [英] Save order of UITableViewCells

查看:115
本文介绍了保存UITableViewCells的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在tableview中添加了选项来对单元格进行排序/重新排序。我使用了本教程: http://www.ioscreator.com/教程/重新排序,排表 - 视图 - iOS8上,迅速。现在我想问一下如何保存细胞的分类/顺序?我还使用Core Data和 fetchedResultsController

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.

推荐答案

添加一个额外的属性到用于存储排序顺序的Core Data模型对象。例如,您可以拥有 orderIndex 属性:

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

最后,更新UITableViewDataSource方法中的 orderIndex 属性:

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

这篇关于保存UITableViewCells的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆