Ios 使用Swift在核心数据中自动重新排序UICollectionView
我有一个应用程序使用UICollectionView,当用户点击并按住某个单元格时,它允许用户切换并重新排列该单元格的位置(类似于iOS允许您在主屏幕上重新排列应用程序的方式) 当然,顺序中的更改不会被保存,当您离开视图并返回时,它会返回到原来的顺序。我的印象是,有一种方法可以在UITableView中自动保存新的单元格顺序,而无需在核心数据中明确写出所有内容 如何在UICollectionView中实现这一点?或者这是不可能的,我将不得不手动将所有内容写入核心数据 编辑:当前相关代码:Ios 使用Swift在核心数据中自动重新排序UICollectionView,ios,iphone,swift,uicollectionview,Ios,Iphone,Swift,Uicollectionview,我有一个应用程序使用UICollectionView,当用户点击并按住某个单元格时,它允许用户切换并重新排列该单元格的位置(类似于iOS允许您在主屏幕上重新排列应用程序的方式) 当然,顺序中的更改不会被保存,当您离开视图并返回时,它会返回到原来的顺序。我的印象是,有一种方法可以在UITableView中自动保存新的单元格顺序,而无需在核心数据中明确写出所有内容 如何在UICollectionView中实现这一点?或者这是不可能的,我将不得不手动将所有内容写入核心数据 编辑:当前相关代码: @IB
@IBOutlet weak var groupCollection: UICollectionView!
var longPressGesture : UILongPressGestureRecognizer?
var newGroupOrderNum : Int?
let indexPath : IndexPath = []
var aryGroup : NSMutableArray!
func handleLongGesture(gesture: UILongPressGestureRecognizer) {
switch(gesture.state) {
case UIGestureRecognizerState.began:
guard let selectedIndexPath = self.groupCollection.indexPathForItem(at: gesture.location(in: self.groupCollection)) else {
break
}
groupCollection.beginInteractiveMovementForItem(at: selectedIndexPath)
case UIGestureRecognizerState.changed:
groupCollection.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
case UIGestureRecognizerState.ended:
groupCollection.endInteractiveMovement()
var timestamp: Date {
return Date()
}
let creationTime = timestamp
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entity = NSEntityDescription.entity(forEntityName: "Group", in:managedContext)
let group = NSManagedObject(entity: entity!, insertInto: managedContext)
let orderChangeGroup = aryGroup.object(at: indexPath.row)
group.setValue(orderChangeGroup, forKey: "groupOrderNum")
do {
try managedContext.save()
}
catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
group.setValue(creationTime, forKey: "creationTime")
default:
groupCollection.cancelInteractiveMovement()
}
}
我认为您需要在完成订购后手动将其保存到核心数据:
let context = self.fetchedResultsController.managedObjectContext
let event = self.fetchedResultsController.object(at: indexPath)
event.ordering = indexPath.row
do { try context.save() }
catch { }
我想我有一个版本的你所说的上面(刚刚编辑)。在控制台中没有输出的情况下拖放后,我崩溃了。这表明let OrderChangeGroup是个问题,尽管我不确定问题出在哪里。在线程1下显示:“0 indexath.section.getter”。有什么想法吗?也许你想要的是
NSFetchedResultsController
。它将为任何NSManagedObjectContext中的所有更新/插入/删除提供细粒度通知?