swift - 在 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
}
}
真的感谢美联社
解决方案
问题在于这部分:
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 不知道现在应该有更多行。
推荐阅读
- powershell - 如何从函数中获取结果
- php - PHP 密码验证
- python-3.x - 如何将 telnet 输出日志保存到文本文件
- django - Django Faker 递归外键
- power-automate - Power 自动生成 Microsoft Power Automate 上特定 Dropbox 文件夹的链接?云或桌面
- python-3.x - Python Pulp 线性规划最小最大范围
- java - 当我尝试使用 BufferedReader 读取输入时,为什么会出现 NullPointerException?
- python - 根据列删除重复项,但另一列必须相同
- c++ - 新手:在 Visual C++ MFC 应用程序中显示/隐藏 STATIC TEXT 对象的代码
- http - 如何计算 Confluent 云 http sink 连接器的 Max Retries 和 Retry backoff 配置?