【问题标题】:Invalid update: invalid number of rows in section UITableView problem无效更新:UITableView 部分行数无效问题
【发布时间】:2021-06-16 18:59:10
【问题描述】:

我正在玩下面的表格(我已经看到了关于这个主题的多个主题,但无法回答我的问题):

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 移出)。"

我假设我应该以某种方式更新数据源,但是由于在我的情况下我为部分中的行返回 const 值,有没有办法更新部分中的行数? (部分中的 numberOfRows 只返回不可变的值)。谢谢

【问题讨论】:

  • 您不能在一个部分中同时拥有固定和可变数量的行;如果您希望能够添加行,您需要在numberOfRows()中返回正确的行数

标签: ios swift uitableview


【解决方案1】:

在我的例子中,我返回 const 值

给你!如果您要修改需要变量

的行数

例如

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)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-04
    • 2013-07-28
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    • 2015-07-01
    相关资源
    最近更新 更多