2016-12-29 89 views
5

我有一個使用UICollectionView的應用程序,當用戶點擊並保持單元格時,它允許用戶轉移並重新排列該單元格的位置(類似於iOS允許您在您的主屏幕上重新排序應用程序)。使用Swift自動重新排列核心數據中的UICollectionView

當然,訂單的更改並未保存,當您離開視圖並返回時,它會返回到原來的順序。我覺得有一種方法可以在UITableView中自動保存單元格的新順序,而無需在Core Data中明確寫出所有內容。

我該如何在UICollectionView中做到這一點?或者這是不可能的,我將不得不手動將所有內容寫入Core Data?

編輯:當前相關代碼:

@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() 
    } 
} 
+0

也許'NSFetchedResultsController'是你所追求的。它會給你所有更新/插入/刪除任何NSManagedObjectContext細粒度的通知? –

回答

1

我認爲你需要手動將它保存到核心數據排序完成後:

let context = self.fetchedResultsController.managedObjectContext 
let event = self.fetchedResultsController.object(at: indexPath) 
event.ordering = indexPath.row 
do { try context.save() } 
catch { } 
+0

我*想*我有一個你上面談論的版本(剛剛編輯)。在拖放控制檯中沒有輸出後,我崩潰了。它顯示讓OrderChangeGroup成爲問題線,雖然我不確定問題是什麼。在線程1下它顯示:「0 IndexPath.section.getter」。有什麼想法嗎? – user3246092