【发布时间】:2016-09-18 23:38:47
【问题描述】:
我正在尝试使用 UITableView 从数组中删除项目,但是 UITableView 有多个部分,并且在删除单元格时我不断收到以下错误
致命错误:索引超出范围
为:
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)]
但我得到了错误:
不能用索引类型为“[Int]”类型的值下标 'NSIndexPath'
【问题讨论】:
标签: ios swift uitableview