How to enable swipe to delete cell in a TableView?

后端 未结 13 2662
悲哀的现实
悲哀的现实 2020-12-07 21:40

I have a UIViewController that implements TableViews delegate and datasource protocols. Now I want to add \"swipe to delete\" gesture to cells.

13条回答
  •  半阙折子戏
    2020-12-07 22:35

    If you are using an NSFetchedResultsControllerDelegate to populate the table view, this worked for me:

    • Make sure tableView:canEditRowAtIndexPath returns true always
    • In your tableView:commitEditingStyle:forRowAtIndexPath implementation, do not delete the row directly from the table view. Instead, delete it using your managed object context, e.g.:

      if editingStyle == UITableViewCellEditingStyle.Delete {
          let word = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Word
          self.managedObjectContext.deleteObject(word)
          self.saveManagedObjectContext()
      }
      
      func saveManagedObjectContext() {
          do {
              try self.managedObjectContext.save()
          } catch {
              let saveError = error as NSError
              print("\(saveError), \(saveError.userInfo)")
          }
      }
      

提交回复
热议问题