OGeek|极客世界-中国程序员成长平台

标题: ios - 尝试将第 3 行插入第 0 节,但更新后第 0 节中只有 3 行 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:08
标题: ios - 尝试将第 3 行插入第 0 节,但更新后第 0 节中只有 3 行

may tableView 有点奇怪

我有

在我的委托(delegate)中,我有

var editingIndexPath: IndexPath?

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if let editingIndexPath = editingIndexPath {
            return datasource.count + 1
        } else {
            return datasource.count
        }

    }

在我的 didSelect 我有

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

            if let oldEditingIndexPath = editingIndexPath {
                    self.editingIndexPath = nil
                    tableView.reloadData()
                    self.editingIndexPath = IndexPath(row: indexPath.row + 1, section: 0)
                    tableView.insertRows(at: [self.editingIndexPath!], with: .top)
            } else {
                editingIndexPath = IndexPath(row: indexPath.row + 1, section: 0)
                if let editingIndexPath = editingIndexPath {
                    tableView.insertRows(at: [editingIndexPath], with: .top)
                }
            }
    }

tableView.reloadData() 报错后崩溃的问题

'attempt to insert row 3 into section 0, but there are only 3 rows in section 0 after the update'

我不明白。 TableView 具有执行插入所需的完全相同的行数。我将属性设置为 nil 然后重新加载表,通过这个操作我将表的行数减少到两个。然后我再次将 editingIndexPath 设置为非零值信号委托(delegate)方法,它应该使用 count + 1。但它以同样的方式失败。

同样有趣的是,相同的代码但没有重新加载之前永远不会失败

            editingIndexPath = IndexPath(row: indexPath.row + 1, section: 0)
            if let editingIndexPath = editingIndexPath {
                tableView.insertRows(at: [editingIndexPath], with: .top)
            }

这里发生了什么?



Best Answer-推荐答案


表格 View 的第 0 部分(第 1 行、第 1 行、第 3 行)有 numberOfRowsInSection 3。在尝试插入超过 numberOfRowsInSection 计数的 Row4 时,抛出上述错误

这可能会更好(注意:毫无逻辑的意图)

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     // better to check with datasource array elements count
     if indexPath.row + 1 < tableView.numberOfRows(inSection: indexPath.section) {
          self.editingIndexPath = IndexPath(row: indexPath.row + 1, section: 0)
          tableView.insertRows(at: [self.editingIndexPath!], with: .top)
     } 
  }

关于ios - 尝试将第 3 行插入第 0 节,但更新后第 0 节中只有 3 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46975985/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4