【问题标题】:attempt to insert row 3 into section 0, but there are only 3 rows in section 0 after the update尝试将第 3 行插入第 0 节,但更新后第 0 节中只有 3 行
【发布时间】:2018-04-12 15:28:53
【问题描述】:

may tableView 有点奇怪

我有

在我的委托中,我有

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() 报错后崩溃的问题

'尝试将第3行插入第0节,但更新后第0节只有3行'

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

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

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

这里发生了什么?

【问题讨论】:

  • 您为什么将tableView.reloadData() right after setting the editingIndexPath` 称为nil?您试图采取的行为有点不清楚。您是否试图始终为 editingIndexPath 提供价值?
  • 主要是为了调试,我有语句在 tableview 重新加载后打印行数,它打印了 2

标签: ios uitableview


【解决方案1】:

表格视图的第 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)
     } 
  }

【讨论】:

  • 行数从 1 开始,而不是 0
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多