ios - fatal error : Index out of range when using UITableView with multiple sections

标签 ios swift uitableview

我正在尝试使用 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/

相关文章:

swift - 创建 json swift 应用程序 : fatal error: found nil when unwrapping json

macos - 使用 Swift 获取已安装的卷列表?

swift - 如何在单例类中共享变量

ios - 当滚动/索引超出数组范围时 UITableView 崩溃

ios - 在模拟器上运行时为"No installed provisioning profiles match the installed iOS signing identities."

ios - XCode,按下图像时显示带有计时器的文本

ios - ios开发中如何消费wcf服务

ios - shouldChangeCharactersInRange 从 UITextField 返回第二个字符

ios - 我想要一个 UIScrollView 内部的 UITableView 延伸到 UIScrollView 的底部,而不是被初始屏幕切断

objective-c - 虚拟警告:不支持的配置最小字体大小大于当前字体大小