Using long press gesture to reorder cells in tableview?

前端 未结 6 553
灰色年华
灰色年华 2021-02-04 03:35

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 essent

6条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-04 04:09

    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) {
        }
    }
    

提交回复
热议问题