【问题标题】:Inserting Rows crashes in Swift在 Swift 中插入行崩溃
【发布时间】:2018-10-10 15:17:54
【问题描述】:

我在 TableView 中插入单元格时遇到崩溃。我试过下面的链接,但不确定是什么问题

Link1Link2Link3 等等

下面是我的代码

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return names.count 

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = names[indexPath.row]
    return cell
}

数据源代码如下

   private var names: [String] = (50...99).map { String($0) }


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
            self.appendCells()
        }

    }

    private func appendCells() {

        names = (0...49).map { String($0) } + names
        customTableView.beginUpdates()
        let indexPat = IndexPath(row: names.count - 1, section: 0)
        customTableView.insertRows(at: [indexPat], with: .fade)
        customTableView.endUpdates()

    }

我无法理解我在这里缺少什么。对不起,如果我做傻事。如果我需要解释更多,请告诉我。

我收到错误:

原因:'无效更新:第 0 节中的行数无效。更新后现有节中包含的行数 (100) 必须等于更新前该节中包含的行数(50),

【问题讨论】:

  • 与往常一样,beginUpdates / endUpdates 对于单个 insert/delete/move 操作毫无意义。

标签: swift uitableview


【解决方案1】:

问题在于您添加到数据模型的值的数量与您添加到表视图的行数不匹配。

行:

names = (0...49).map { String($0) } + names

为您的数据模型添加 50 个新值。

但是你只告诉表格视图有一个新行。这就是错误消息中告诉您的内容。

您需要一个循环来构建一个包含 50 个索引路径的数组。

private func appendCells() {
    names = (0...49).map { String($0) } + names
    var paths = [IndexPath]()
    for row in 0...49 {
        let indexPath = IndexPath(row: row, section: 0)
        paths.append(indexPath)
    }
    customTableView.insertRows(at: paths, with: .fade)
}

【讨论】:

    【解决方案2】:

    错误清楚地表明您正在添加 indexPath,其中 row = 99,section = 0,而实际上,它的最大 indexpath 包含值:row = 49,section = 0。

    在插入之前,tableview 调用数据源方法numberOfRowsInSection - 此方法必须返回您更新、更大的数组计数 (100),而不是较早的 (50)。

    【讨论】:

    • 这是不正确的。原始数据的值为 50...99。当向数据模型中添加了 50 个以上的值但仅向表视图中添加了一行时,就会发生错误。
    • 我指的是行数,而不是名称数组中的值。
    • 对,但问题是当数据模型中添加了 50 行时,表视图中只添加了一行。
    • @rmaddy 是的,我的回答似乎指出了错误的索引路径,不是吗?
    • 但这并没有错。数据模型中现在有 100 个值,因此具有 99 行的索引路径是有效的。同样,这不是问题,看看我的答案。
    【解决方案3】:

    1) 'appendCells' 之前的模型有 50 个名称。 2) 调用后,您的模式等于 100 个名称计数,但您只在索引路径 = 99 处插入一个单元格?您需要再插入 50 行而不是 1 行。

    【讨论】:

      【解决方案4】:

      我遇到了这个问题,它使用以下方法工作

       func insertRow(entries: [String]) {
              tableView.performBatchUpdates({
                  self.tableView.insertRows(at: [IndexPath(row: entries.count - 1, section: 0)], with: .bottom)
              }, completion: nil)
          }
      

      【讨论】:

        猜你喜欢
        • 2013-01-09
        • 1970-01-01
        • 2014-02-27
        • 1970-01-01
        • 2015-12-17
        • 1970-01-01
        • 1970-01-01
        • 2015-11-20
        • 2012-10-01
        相关资源
        最近更新 更多