【发布时间】:2017-06-09 10:05:17
【问题描述】:
我有一个 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 模型中的索引属性。目前,节只有这个排序键,节内的项目没有。
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "section.index", ascending: false)]
let resultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath:"section.name", cacheName: nil)
【问题讨论】:
-
您如何对项目进行排序以在集合视图中显示它们?
-
我已经更新了这个问题。部分的排序基于部分模型的属性。
标签: ios swift core-data uicollectionview nsfetchedresultscontroller