Invalid update: invalid number of rows in section UITableView 问题

Invalid update: invalid number of rows in section UITableView problem

我正在玩一个 table 如下(我已经看到关于这个主题的多个线程,但无法回答我的问题):

func numberOfSections(in _: UITableView) -> Int {
        3
    }

func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
        return 3
    } else if section == 1 {
        return 4
    } else {
        return 2
    }
}

然后在单击一个单元格后,我想将一个新单元格插入行索引 0 处的同一部分。我写了以下内容:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     tableView.insertRows(at: [IndexPath(row: 0, section: indexPath.section)], with: .left)
   }

我收到这个错误: 异常 NSException *“无效更新:第 0 部分中的行数无效。更新 (3) 后现有部分中包含的行数必须等于更新 (3) 前该部分中包含的行数,加上或减去从该部分插入或删除的行数(1 插入,0 删除),加上或减去移入或移出该部分的行数(0 移入,0 移出)。"

我假设我应该以某种方式更新数据源,但由于在我的情况下我 return 节中行的常量值有没有办法更新节中的行数? (第 numberOfRows 部分只有 returns immutable 值)。谢谢

in my case I return const values

给你!如果你要修改你需要的行数 variables

例如

var sections = [3,4,2]

func numberOfSections(in _: UITableView) -> Int {
    return sections.count
}

func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
    return sections[section]
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    sections[indexPath.section] += 1
    tableView.insertRows(at: [IndexPath(row: 0, section: indexPath.section)], with: .left)
}