繁体   English   中英

在UICollectionView + NSFetchedResultsController中对单元格重新排序

[英]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 ,由于此属性是只读的,因此无法正常运行。 怎样做拖放与下降的最好办法UICollectionViewNSFetchedResultsController

编辑:

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数组中对象的顺序。 该数组基于您的排序描述符进行排序,并且是只读的。

因此,您有两种可能的选择:

  1. 更改您在排序描述符中使用的属性,以便新的排序结果将与拖放操作的结果匹配。 保存更改, NSFetchedResultsController委托方法将触发。 您已经更改了顺序,并且fetchedObjects结果控制器会将其反映在其fetchedObjects数组中。
  2. 不要使用NSFetchedResultsController ,只需进行提取并将结果保存在自己的数组中即可。 重新排列您自己数组中的项目,但不要更改Core Data关心的任何内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM