保存 UITableViewCells 的顺序

Posted

技术标签:

【中文标题】保存 UITableViewCells 的顺序【英文标题】:Save order of UITableViewCells 【发布时间】:2015-08-31 22:53:32 【问题描述】:

我在表格视图中添加了对单元格进行排序/重新排序的选项。我使用了本教程:http://www.ioscreator.com/tutorials/reordering-rows-table-view-ios8-swift。现在我想问一下如何保存单元格的排序/顺序?我还使用 Core Data 和 fetchedResultsController

【问题讨论】:

虽然您在链接中隐含地包含了您采取的步骤,但您应该将其写出来,而不是要求访问者去其他地方收集您所做的事情。 虽然它在 Objective C 中,this tutorial 可能会有所帮助。 【参考方案1】:

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

class MyItem: NSManagedObject 

    @NSManaged var myOtherAttribute: String
    @NSManaged var orderIndex: Int32


然后,在排序描述符中使用该属性来获取结果控制器的获取请求:

fetchRequest.sortDescriptors = [NSSortDescriptor(key: "orderIndex", ascending: true)]

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

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 的顺序的主要内容,如果未能解决你的问题,请参考以下文章

在 Wordpress 后端保存 jQuery UI 可排序顺序

如何在 php 中保存 jquery ui 可排序顺序

jQuery UI 可排序的默认顺序

检索未查看的 UITableViewCells 的数据源

使用字典中的“值”填充 UITableViewCells 的问题

滚动 UITableView 时 iOS Expanded/Selected Custom UITableViewCells 状态变化