我是iOS编程的新手,尤其是在核心数据方面。我有一个带To-Do列表的应用程序,我在ViewController里面使用了TableView。我需要用拖拽的方式对tableview单元格进行重新排序,但同时又不需要编辑模式,所以我选择了这个库。所以我选择了这个库: https:/github.comsivu22LongPressReorder。我需要保存重新排序的表格视图单元格的位置,我已经尝试了StackOverflow上和互联网上所有与Swift相关的解决方案.目前我在一个名为 "Inbox "的实体内有一个名为 "orderPosition "的属性。
从上面的库中,我给我的ViewController添加了两个函数(见下图)。
override func positionChanged(currentIndex: IndexPath, newIndex: IndexPath) {
// currentIndex and newIndex rows are swapped, implement accordingly
}
override func reorderFinished(initialIndex: IndexPath, finalIndex: IndexPath) {
// Gesture is finished and cell is back inside the table at finalIndex position
}
我在第二个func里面添加了代码,因为它是在手势完成后调用的。
下面是我在ViewController扩展中使用的代码。
override func positionChanged(currentIndex: IndexPath, newIndex: IndexPath) {
// currentIndex and newIndex rows are swapped, implement accordingly
}
override func reorderFinished(initialIndex: IndexPath, finalIndex: IndexPath) {
// Gesture is finished and cell is back inside the table at finalIndex position
self.loadSaveData()
let task = tasks[initialIndex.row]
tasks.remove(at: initialIndex.row)
tasks.insert(task, at: finalIndex.row)
var i = 0
for task in tasks {
i += 1
task.setValue(i, forKey: "orderPosition")
}
do {
try self.manageObjectContext.save()
} catch let error as NSError {
print("Error While Deleting Note: \(error.userInfo)")
}
}
Where:
func loadSaveData() {
let inboxRequest: NSFetchRequest<Inbox> = Inbox.fetchRequest()
inboxRequest.sortDescriptors = [NSSortDescriptor(key: "orderPosition", ascending: true)]
do{
inboxArray = try manageObjectContext.fetch(inboxRequest)
self.tableView1.reloadData()
}catch
{
print("Could not load save data: \(error.localizedDescription)")
}
}
这是inboxArray, manageObjectContext和tasks的声明:
var tasks: [NSManagedObject] = []
var inboxArray = [Inbox]()
var manageObjectContext: NSManagedObjectContext!