【问题标题】:fatal error: Index out of range when using UITableView with multiple sections致命错误:使用具有多个部分的 UITableView 时索引超出范围
【发布时间】: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


    【解决方案1】:

    您在错误的数组上调用 remove。您在 sectionItems 数组上调用它,而不是在 sectionItems 数组中包含的数组。

    您需要先使用indexPath.section 来检索适当的数组,然后调用remove:

    self.sectionItems[indexPath.section].remove(at:indexPath.row)
    

    【讨论】:

    • 对不起,但我怎么能从 sectionItems 中获取 indexPath.row 的字符串值,数组中的数组,我要从中删除?
    • 如果我想创建一个新属性说 let item = 不管 self.sectionItems[indexPath.section].remove(at:indexPath.row) 是
    • let currentValue = self.sectionItems[indexPath.section][indexPath.row] and self.sectionItems[indexPath.section].append("New Item") 如果你只是想替换值self.sectionItems[indexPath.section][indexPath.row]="new value"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多