Ios 拖放适用于不带UITableViewDropDelegate的UITableView

Ios 拖放适用于不带UITableViewDropDelegate的UITableView,ios,swift,uitableview,uikit,Ios,Swift,Uitableview,Uikit,根据苹果的文档,要支持对UITableView进行拖放,我必须实现UITableViewDragDelegate和UITableViewDropDelegate。我只实现了UITableViewDragDelegate,并为tableView(u:itemsForBeginning:at:)(它返回空列表)。但这个解决方案是有效的 它为什么有效 import UIKit class TableViewController: UITableViewController, UITa

根据苹果的文档,要支持对
UITableView
进行拖放,我必须实现
UITableViewDragDelegate
UITableViewDropDelegate
。我只实现了
UITableViewDragDelegate
,并为
tableView(u:itemsForBeginning:at:)
(它返回空列表)。但这个解决方案是有效的

它为什么有效

    import UIKit

    class TableViewController: UITableViewController, UITableViewDragDelegate {
        var data = [1, 2, 3, 4, 5]

        // MARK: - Table view drag delegate
        func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
            // fake implementation with empty list
            return []
        }

        // MARK: - Table view data source
        override func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }

        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return data.count
        }

        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            cell.textLabel?.text = "Cell \(data[indexPath.row])"
            return cell
        }

        override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
            let tmp = data[sourceIndexPath.row]
            data.remove(at: sourceIndexPath.row)
            data.insert(tmp, at: destinationIndexPath.row)
        }

        // MARK: - View controller
        override func viewDidLoad() {
            super.viewDidLoad()
            self.tableView.dragInteractionEnabled = true
            self.tableView.dragDelegate = self
        }
    }
它不起作用。你看到的不是拖放

您将看到使用“重新排序控件”重新排列行。这种机制非常古老;在创建拖放之前,它已经存在了很多年。这就是你实施该计划的效果

override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
它是一种UITableViewDataSource方法;它与拖放无关。见:

如果删除该方法,旧的行重排机制将停止运行,现在将使用拖放和

override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {

将会很有意义。

谢谢你的回答。我知道重新排序控制,但问了这个问题,因为行在重新排序期间没有它。我添加了gif来解释它。如果我错了,很抱歉,但您是否真的按照我的建议删除了
moveRowAt
?如果没有此方法,它真的不起作用。但是,如果不为表视图指定拖动委托,它也无法工作,如果使用旧的重新排序方法,看起来很奇怪。当然,但我相信我已经回答了这个问题。你的问题是:我禁止使用空数组拖放,但我仍然可以对行重新排序。我的答案是:这是因为您已经加入了
moveRowAt
的实现。我的答案是正确的。