我正在尝试使用 UITableView 从数组中删除项目,但是 UITableView 有多个部分,删除单元格时我不断收到以下错误
fatal error: Index out of range
对于:
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
// Delete the row from the data source
if editingStyle == UITableViewCellEditingStyle.delete {
if let table = self.table {
self.sectionItems.remove(at: [(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row])
table.deleteRows(at: [indexPath], with: UITableViewRowAnimation.left )
}
}
}
这是我填充 UITableView 的方式
let sections = ["One", "Two", "Three", "Four"]
var sectionItems = [ [String](), [String](), [String](), [String]() ]
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (self.sectionItems[section] as AnyObject).count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell
cell.textLabel!.text = self.sectionItems[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
return cell
}
有人知道我错在哪里吗?
我试着改变
table.deleteRows(at: [indexPath], with: UITableViewRowAnimation.left )
到
table.deleteRows(at: [(indexPath as NSIndexPath).section][(indexPath as NSIndexPath)]
但是我得到了错误:
Cannot subscript a value of type '[Int]' with an index of type 'NSIndexPath'
最佳答案
您在错误的数组上调用了 remove
。您是在 sectionItems
数组上调用它,而不是 sectionItems
数组中包含的数组。
您需要先使用 indexPath.section
检索适当的数组,然后调用 remove:
self.sectionItems[indexPath.section].remove(at:indexPath.row)
关于ios - fatal error : Index out of range when using UITableView with multiple sections,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39563619/