[英]Reorder cells in UICollectionView + NSFetchedResultsController
我有一个UICollectionView,它显示带有NSFetchedResultsController的CoreData中的实体。 如屏幕截图所示,用户可以选择多个带有边框标记的单元格。
我的模型基本上只有一个字符串和一个布尔值,用于通过UICollectionView处理选择。
var url: String
var selected: Bool
var section:Section
我已经实现func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath)
以支持UICollectionViewCells
重新排序。 拖放操作效果很好,但是我很难将已移动的项目保存到CoreData中。 我必须在模型中添加position
属性吗?
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
var sourceArray = self.fetchedResultController.fetchedObjects
let item = sourceArray?.remove(at: sourceIndexPath.item)
sourceArray?.insert(item!, at: destinationIndexPath.row)
coreData.saveContext()
}
我尝试直接修改fetchedResultsController.fechtedObjects
,由于此属性是只读的,因此无法正常运行。 怎样做拖放与下降的最好办法UICollectionView
和NSFetchedResultsController
。
编辑:
UICollectionView
初始排序基于Section
模型中的index属性。 当前,各部分只有此排序键,而各部分中没有任何项。
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "section.index", ascending: false)]
let resultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath:"section.name", cacheName: nil)
正如您所发现的,您不能仅仅告诉NSFetchedResultsController
更改其fetchedObjects
数组中对象的顺序。 该数组基于您的排序描述符进行排序,并且是只读的。
因此,您有两种可能的选择:
NSFetchedResultsController
委托方法将触发。 您已经更改了顺序,并且fetchedObjects
结果控制器会将其反映在其fetchedObjects
数组中。 NSFetchedResultsController
,只需进行提取并将结果保存在自己的数组中即可。 重新排列您自己数组中的项目,但不要更改Core Data关心的任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.