当用户在UITableView中拖动项目时,获取单元格的索引路径



我需要实现一个功能,其中单元格显示它们在表上的位置。当用户拖动单元格时,我需要用新位置更新数字。我正在使用Drag&删除从iOS 11开始可用的API,但似乎没有办法在用户拖动单元格时获得更新的索引路径。每个单元格都保持与拖动开始前相同的索引路径。

只是为了用一个例子更好地解释这一点。我有以下清单:

  1. 项目A
  2. 项目B
  3. 项目C

现在,如果我拖动项目C并将其放在项目A和B之间,我需要单元格在用户拖动它时实时更新该数字。因此,实时数字将变为:

  1. 项目A
  2. 项目C
  3. 项目B

此外,我需要能够设置拖动单元格的背景色。我尝试过使用拖动预览参数的背景颜色,但这只设置边框颜色,而不是整个单元格的背景颜色。

func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal {
if session.localDragSession != nil { // Drag originated from the same app.
if currentDestinationIndexPath != destinationIndexPath {
//Here I need to update the rows so they display their new position 
//in the table but all rows are still reported having same index path as before the drag started
}
return UITableViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
}

return UITableViewDropProposal(operation: .cancel, intent: .unspecified)
}
func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
currentDestinationIndexPath = indexPath
return [UIDragItem(itemProvider: NSItemProvider())]
}
要实现这一点,您必须实现两个TableViewDelegateMethod

在更改单元格的位置时,还必须更新表视图的数据源。

override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
//products is my datasource i.e [String]
let productToMove = products[sourceIndexPath.row]
products.insert(productToMove, at: destinationIndexPath.row)
products.remove(at: sourceIndexPath.row)
}

最新更新