首页 > 解决方案 > Swift 5:在 TableView 中将单元格从一个部分移动到另一部分

问题描述

我正在做一些表格视图练习。我想实现一个函数,通过使用 moveRowAt 方法将一个单元格从一个部分移动到另一个部分。当我在同一部分中移动/排列一个单元格时,它工作正常。但是,当我将一个单元格从一个部分移动到另一个部分时,它会给我一个这样的错误:在此处输入图像描述

这是 moveRowAt 函数:

    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath)
    {
        // Move data
        let todo = todos[fromIndexPath.section][fromIndexPath.row]
        todos[fromIndexPath.section].remove(at: fromIndexPath.row)
        // move from one section to another section
        if to.section != fromIndexPath.section
        {
            todos[to.section].insert(todo, at: to.row)
            //        Update View
            tableView.beginUpdates()
            tableView.moveRow(at: fromIndexPath, to: to)
            tableView.endUpdates()
        }
        else
        {
            todos[fromIndexPath.section].insert(todo, at: to.row)
            //        Update View
            tableView.beginUpdates()
            tableView.moveRow(at: fromIndexPath, to: to)
            tableView.endUpdates()
        }

    }

todos 的声明是:

struct ToDo {
    var name = ""
    var checked = false
    var details: String = ""
}

var todos: [[ToDo]]

感谢您的帮助和分享您的想法!

标签: iosswiftuitableview

解决方案


你不应该打电话

tableView.moveRow(at: fromIndexPath, to: to)

自己因为这将导致递归循环只需执行删除和插入


推荐阅读