I have an application that uses a UICollectionView, and when the user selects and holds the cell, it allows the user to move around and rearrange the position of that cell (just like iOS allows you to change the order of applications on the main screen).
Of course, the change in the order is not saved, and it reverts to its previous order when you leave the view and return. I had the impression that there is a way to automatically save the new cell order in a UITableView without explicitly writing everything in Core Data.
How to do this in a UICollectionView? Or is it impossible, and I have to write everything in Core Data manually?
Edit: Current Corresponding 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() } }
source share