首页 > 解决方案 > 在 tableView 中出列可重用的 Cell 崩溃

问题描述

我在表格视图上添加新单元格时遇到了一些麻烦。

奇怪的是,一旦该功能完美运行而没有问题,我就运行它,如果我第二次运行它,它会因此错误而崩溃。

* 由于未捕获的异常“NSRangeException”而终止应用程序,原因:“* -[__NSSingleObjectArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]”

这是我的代码:

override func viewWillAppear(_ animated: Bool) {
    if prodottoDaAggiungere != nil {
        prodotti.append(prodottoDaAggiungere!)
        let indexPath = IndexPath(row: prodotti.count-1, section: 1)
        tableView.insertRows(at: [indexPath], with: .fade) // ?
        prodottoDaAggiungere = nil
    }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if indexPath.row < prodotti.count && indexPath.section == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ProdottoTableViewCell", for: indexPath) as! ProdottoTableViewCell // Crash :|
        let indexRow = indexPath.row // Fix
        cell.title.text = "\(prodotti[indexRow].prodotto.nome!) - \(prodotti[indexRow].prodotto.marca!)"
        cell.subtitle.text = "\(prodotti[indexRow].prodotto.formati[prodotti[indexRow].formato].dimensione) \(prodotti[indexRow].prodotto.unitàMisura!) - \(prodotti[indexRow].prodotto.formati[prodotti[indexRow].formato].prezzo) €"
        cell.number.text = Int(cell.stepper.value).description // 1
        cell.stepper.addTarget(self, action: #selector(stepperChanged), for: .valueChanged)
        return cell
    }

    return super.tableView(tableView, cellForRowAt: indexPath)
}

使用断点我在 dequeueReusableCell 上创建了应用程序崩溃,但我不明白为什么,有人可以告诉我为什么这段代码会崩溃?

这是我的 tableView numberOfRowsInSection 函数:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    if section == 0 {
        return 1
    } else if section == 1 {
        return 1+prodotti.count
    } else {
        return 0
    }
}

故事板

细胞

结果

真的感谢美联社

标签: swiftuitableview

解决方案


问题在于这部分:

let indexPath = IndexPath(row: prodotti.count, section: 1)

如果prodotti.count是 2,那么当计数为 2 时,您正在尝试滚动到索引为 2 的行。您需要切换它以便您要去count - 1,如下所示:

let indexPath = IndexPath(row: prodotti.count - 1, section: 1)

此外,您将需要prodotti使用您添加的新项目来更新数组。由于您在该部分中的行数是prodotti+ 2,它在前两次工作,但是由于您实际上没有增加 的大小prodotti,所以 tableview 不知道现在应该有更多行。


推荐阅读