2016-12-29 6 views
5

私はUICollectionViewを使用するアプリケーションを持っています。ユーザーがセルをタップして保持すると、ユーザーはそのセルの位置を移動して並べ替えることができますあなたのホームスクリーン上のアプリケーションを並べ替える)。SwiftでコアデータのUICollectionViewを自動的に並べ替える

もちろん、順序の変更は保存されず、ビューを終了して戻ってくると元の状態に戻ります。私は、Core Dataに明示的に書き込むことなく、自動的に新しいセルの順序をUITableViewに保存する方法があるという印象を受けました。

UICollectionViewでどうすればいいですか?それとも不可能なのですか?私はコアデータにすべてを手動で書き込まなければなりませんか?

編集:現在関連のあるコード:

@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

関連する問題