重新排列 UITableView 中的单元格并保存更改
Posted
技术标签:
【中文标题】重新排列 UITableView 中的单元格并保存更改【英文标题】:Rearranging Cells in UITableView Bug & Saving Changes 【发布时间】:2015-07-13 15:28:30 【问题描述】:在我的 custom UITableView
中重新排列单元格时,我遇到了一个错误,例如
如果我重新排列 1、2、3、4、5 并将单元格 1 移动到单元格 5 所在的末尾,那么会发生所有单元格将自己重命名为它们要替换的单元格。因此,新订单不是 2,3,4,5,1,而是 1(2),2(3),3(4),4(5),1(移动单元格)。
在我的核心数据模型中,我有两个实体,一个用于Folder,另一个用于Items。它是NSSet
类型的对多关系,因此文件夹可以有许多项目。项目有一个名为 index
的属性,类型为 Int
,表示数组中的项目顺序,并且文件夹具有名为 arrayOfItems
的瞬态属性,该属性是可转换的类型。这将返回按索引值排序的 Items 数组。
控制台打印出end of didmovecell function
但不是 Moved cell
。
table.didMoveCellFromIndexPathToIndexPathBlock = (fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) -> Void in
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath)
let itemThatMoved = self.selectedFolder.arrayOfItems[sourceIndexPath.row]
self.selectedFolder.arrayOfItems.removeAtIndex(sourceIndexPath.row)
self.selectedFolder.arrayOfItems.insert(itemThatMoved, atIndex:destinationIndexPath.row )
var currentIndex = 0
for item in self.selectedFolder.arrayOfItems
item.index=currentIndex
currentIndex++
println("Moved cell")
println("end of didmovecell function")
任何想法为什么会发生这种情况以及如何将更改保存到我的核心数据模型,例如更新项目索引值。
PS:我已经为我的自定义 UITableView 测试了didMoveCellFromIndexPathToIndexPathBlock
,没有使用核心数据,并带有一个名为 Objects 的基本数组。像这样的东西效果很好;
table.didMoveCellFromIndexPathToIndexPathBlock = (fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) -> Void in
self.objects.exchangeObjectAtIndex(toIndexPath.row, withObjectAtIndex: fromIndexPath.row)
【问题讨论】:
您能说明一下您是如何使用此代码的吗?我不太明白你为什么将 moveRowAtIndexPath 函数包装到块中。另外,你能告诉我是否打印过“移动单元格” 我有一个带有动画的自定义 UITableView 来处理动作,所以table.didMoveCellFromIndexPathToIndexPathBlock
是自定义表格,它是处理动画的方法。正如我在“移动单元格”问题中提到的那样,实际上并没有打印出来,但单元格确实改变了位置。
【参考方案1】:
好的,如果您需要保留这些块,请将您的代码更改为:
table.didMoveCellFromIndexPathToIndexPathBlock = (fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) -> Void in
let itemThatMoved = self.selectedFolder.arrayOfItems[fromIndexPath.row]
self.selectedFolder.arrayOfItems.removeAtIndex(fromIndexPath.row)
self.selectedFolder.arrayOfItems.insert(itemThatMoved, atIndex:toIndexPath.row )
var currentIndex = 0
for item in self.selectedFolder.arrayOfItems
item.index=currentIndex
currentIndex++
// at this point call saveContext() to ensure that rearrangement is saved in Core Data
以前你有一个函数包裹在你的块中。您正在调用该块,但其中的函数从未被调用:)
【讨论】:
太棒了!!男生错误:/应该知道得更好。而且因为我直接处理数据,所以不需要调用额外的保存。 只有当您确定您的数据将在稍后的某个时间点保存时,您才需要调用额外的保存。但是,如果您不确定是否应该在对其进行更改后绝对保存您的上下文:)以上是关于重新排列 UITableView 中的单元格并保存更改的主要内容,如果未能解决你的问题,请参考以下文章