I have an app that uses a UICollectionView and when a user taps and holds on a cell it allows the user to shift around and reorder the position of that cell (similar to how iOS allows you to reorder apps on your home screen).
Of course the change in order is not saved and it goes back to its old order when you leave the view and come back. I was under the impression there is way to automatically save a new order of cells in a UITableView without explicitly writing everything out in Core Data.
How can I do that in a UICollectionView? Or is that not possible and I will have to write everything to Core Data manually?
Edit: Current Pertinent Code:
@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()
}
}
I think you need to manually save it to Core Data after the ordering done:
let context = self.fetchedResultsController.managedObjectContext
let event = self.fetchedResultsController.object(at: indexPath)
event.ordering = indexPath.row
do { try context.save() }
catch { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With