Tutorial on How to Drag and Drop Item from Uitableview to Uitableview

Tutorial on How to drag and drop item from UITableView to UITableView

Hi I've managed to create drag&drop of a row in a UITableView onto another row of the same table. I created a uiImageView representing the moving item (which was not removed from the table) and attached it to the frontmost UIView to made it draggable on the whole screen.
Here are some post about the pains I faced:

  1. UITableView: Drag a row onto another one
  2. UITableView: scrolling programmatically the content view
  3. UITableView: custom gestures make it scrolling no more

Hope this can help ^^

How can I use Drag and Drop to reorder a UITableView?

If you are performing a drag on a single item locally, you can use tableView(_:moveRowAt:to:). In order to do this, you need to implement UITableViewDragDelegate.

Setup

Start by setting your delegates. Setting dragInteractionEnabled is required for iPhones.

func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
tableView.dragDelegate = self
tableView.dragInteractionEnabled = true
}

UITableViewDragDelegate

Notice that the array is returning a single item. If you return more than one item, then the UITableViewDropDelegate methods will be used instead of tableView(_:moveRowAt:to:). You must set a local object.

func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
let dragItem = UIDragItem(itemProvider: NSItemProvider())
dragItem.localObject = data[indexPath.row]
return [ dragItem ]
}

Moving

This is where the moving happens and is actually a part of UITableViewDelegate.

func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
// Update the model
let mover = data.remove(at: sourceIndexPath.row)
data.insert(mover, at: destinationIndexPath.row)
}

You can also use tableView(_:canMoveRow:at:) and tableView(_:targetIndexPathForMoveFromRowAt: toProposedIndexPath:) if needed.

You can read more here...

  • Drag and Drop
  • Adopting Drag and Drop in a Table View

uitableview drag and drop with not moving cells

Your answer is hear,
You can use these step.

Examples of Moving a Row

UITableView Drag & Drop Outside Table = Crash

The Ugly

It seems that you simply need to do a preemptive check, to ensure your indexPath is not nil:

var indexPath = tableView.indexPathForRowAtPoint(locationInView)
if (indexPath != nil) {
//Move your code to this block
}

Hope that helps!



Related Topics



Leave a reply



Submit