Using long press gesture to reorder cells in tableview?

Michael Campsall picture Michael Campsall · Sep 4, 2012 · Viewed 14.3k times · Source

I want to be able to reorder tableview cells using a longPress gesture (not with the standard reorder controls). After the longPress is recognized I want the tableView to essentially enter 'edit mode' and then reorder as if I was using the reorder controls supplied by Apple.

Is there a way to do this without needing to rely on 3rd party solutions?

Thanks in advance.

EDIT: I ended up using the solution that was in the accepted answer and relied on a 3rd party solution.

Answer

Grant Kamin picture Grant Kamin · Jul 26, 2019

They added a way in iOS 11.

First, enable drag interaction and set the drag and drop delegates.

Then implement moveRowAt as if you are moving the cell normally with the reorder control.

Then implement the drag / drop delegates as shown below.

tableView.dragInteractionEnabled = true
tableView.dragDelegate = self
tableView.dropDelegate = self

func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { }

extension TableView: UITableViewDragDelegate {
func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
        return [UIDragItem(itemProvider: NSItemProvider())]
    }
} 

extension TableView: UITableViewDropDelegate {
    func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal {

        if session.localDragSession != nil { // Drag originated from the same app.
            return UITableViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
        }

        return UITableViewDropProposal(operation: .cancel, intent: .unspecified)
    }

    func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {
    }
}