Hes*_*gid 6 iphone uitableview ios swift ios11
我在 iOS 11 上使用新的拖放 API 来重新排序同一应用程序内 tableview 中的单元格。
这是我对UITableViewDragDelegateand的实现UITableViewDropDelegate:
extension TasksViewController: UITableViewDragDelegate {
func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
let string = tasks[indexPath.row]
guard let data = string.data(using: .utf8) else { return [] }
let itemProvider = NSItemProvider(item: data as NSData, typeIdentifier: kUTTypePlainText as String)
let item = UIDragItem(itemProvider: itemProvider)
item.localObject = string
return [item]
}
}
extension TasksViewController: UITableViewDropDelegate {
func tableView(_ tableView: UITableView, canHandle session: UIDropSession) -> Bool {
return true
}
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) {
guard let destinationIndexPath = coordinator.destinationIndexPath,
let dragItem = coordinator.items.first?.dragItem,
let task = dragItem.localObject as? String,
let sourceIndexPath = coordinator.items.first?.sourceIndexPath else {
return
}
tableView.performBatchUpdates({
self.tasks.remove(at: sourceIndexPath.row)
self.tasks.insert(task, at: destinationIndexPath.row)
tableView.deleteRows(at: [sourceIndexPath], with: .none)
tableView.insertRows(at: [destinationIndexPath], with: .none)
})
coordinator.drop(dragItem, toRowAt: destinationIndexPath)
}
}
Run Code Online (Sandbox Code Playgroud)
这工作正常,但有一个奇怪的故障。当最后一个单元格被拖动时,只要它被放下,它就会出现在 tableview 的底部一瞬间然后消失。
我在这里缺少什么?
只需将表删除动画更改为 .automatic,如下所示:
tableView.deleteRows(at: [sourceIndexPath], with: .automatic)
Run Code Online (Sandbox Code Playgroud)
之后就不会再有那么奇怪的动画了。
| 归档时间: |
|
| 查看次数: |
1184 次 |
| 最近记录: |