Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically Reordering UICollectionView in Core Data with Swift

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()
    }
}
like image 330
user3246092 Avatar asked Nov 09 '22 04:11

user3246092


1 Answers

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 { }
like image 105
bubuxu Avatar answered Nov 15 '22 06:11

bubuxu