【发布时间】:2020-02-13 19:31:55
【问题描述】:
我在表格视图中添加新单元格时遇到了一些麻烦。
奇怪的是,当我运行该函数时,如果我第二次运行它,它会因为这个错误而崩溃。
* 由于未捕获的异常 '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
}
}
真的谢谢 美联社
【问题讨论】:
-
能分享一下prodotti数组初始化吗?
-
尝试将 indexPath 行设置为
prodotti.count -1 -
@Mac3n 它再次崩溃并出现同样的错误,但现在我可以使用该功能 2 次,第三次崩溃。
-
能否请您发布 numberOfRowsInSection 函数?
-
永远,永远不要在
cellForRowAt之外打电话给dequeueReusableCell。这完全没有意义——单元格在方法结束时被创建并丢弃——以及beginUpdates/endUpdates。
标签: swift uitableview