我在 Swift iOS 应用程序中有一个 tableView,允许用户对行重新排序。点击“编辑”按钮,可以重新排序或删除行,然后重新点击“编辑”按钮(现在显示为“完成”)以完成该过程。
如果我只是使用 tableView:moveRowAtIndexPath:toIndexPath: 方法,它的工作方式如上所述,并且在点击“完成”时,表会正确显示重新排序的行。但它在返回表时不记得新顺序,因此我在核心数据中添加了一个新的“位置”变量(Int),并且我让表根据该变量自行排序。
我的问题是,在用户移动一行并单击“完成”后,该表立即将其自身重新排序回到之前的状态。因此,在我的代码可以正确捕获新订单并将其重新写入核心数据之前,它正在使用核心数据中的旧(原始)位置变量。
有没有办法在表重新加载之前单击“完成”时捕获此新订单?
这是我处理移动的代码:
func tableView(tableView: UITableView!, moveRowAtIndexPath sourceIndexPath: NSIndexPath!, toIndexPath destinationIndexPath: NSIndexPath!) {
}
这是按下“完成”时调用的代码。我遍历表的每一行,并根据新行重新分配核心数据中人员的位置变量:
for currentIteration in 0..<tableView.numberOfRowsInSection(0) {
var indexPathForCurrentIteration = NSIndexPath(forRow: currentIteration, inSection: 0)
let personAtCurrentIndexIteration = fetchedResultsController.objectAtIndexPath(indexPathForCurrentIteration) as PersonModel
personAtCurrentIndexIteration.position = indexPathForCurrentIteration.row
println("\(personAtCurrentIndexIteration.name) has a position value of \(personAtCurrentIndexIteration.position)")
(UIApplication.sharedApplication().delegate as AppDelegate).saveContext()
tableView.reloadData();
}
当按下“完成”按钮时,会调用上面的方法,但我也尝试在 moveRowAtIndexPath 方法中调用它,但没有成功(相同的结果 - 当按下“完成”按钮时,它会重新加载表的旧顺序)。我也尝试注释掉 reloadData 但没有成功。
我认为我的问题可能在于上面的内容没有捕获新的行顺序,而是仍然获取旧的行顺序。如果是这种情况,那么我不知道让它“等待”获取新行顺序的最简单方法。
我开始考虑的一个较长的解决方法是捕获移动行的初始和最终行值,并据此相应地更新剩余行的值。其中一些代码如下,但我停止了,因为我认为可能有更聪明的方法。
if((sourceIndexPath.row > indexPathForCurrentIteration.row) && (destinationIndexPath.row > indexPathForCurrentIteration.row)) {
//if the moved row was ahead of this row before AND after the move, do nothing (don't change this row's position value)
//println("\(personAtCurrentIndexIteration.name)'s position was unchnaged")
} else if((sourceIndexPath.row > indexPathForCurrentIteration.row) && (destinationIndexPath.row < indexPathForCurrentIteration.row)) {
//if the moved row was ahead of this row before BUT behind it after the move, then this row's position value needs to be bumped up one number
personAtCurrentIndexIteration.position = indexPathForCurrentIteration.row+1
//Etc...
预先感谢您可以提供的任何帮助。