gpt4 book ai didi

swift - 保存 UITableViewCells 的顺序

转载 作者:搜寻专家 更新时间:2023-10-31 08:33:26 25 4
gpt4 key购买 nike

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

最佳答案

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

class MyItem: NSManagedObject {

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

}

然后,在您的已获取结果 Controller 的获取请求的排序描述符中使用此属性:

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

关于swift - 保存 UITableViewCells 的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32321093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com