ios - 如何在 Swift 中从 UITableView 中删除部分?

标签 ios swift uitableview uikit

我是 iOS 和一般编程的新手,正在尝试创建我的第一个应用程序。我已经搜索了一段时间以寻找解决方案,但找不到。我有一个 UITableView,其中的单元格分为几个部分,我想让用户删除这些部分。我在执行它以便删除单元格时没有问题,但是我想在其中有零个单元格时删除一个部分,这给我带来了麻烦。我的 numberOfSectionsInTableView 和 numberOfRowsInSection 方法返回正确的数量。我的 commitEditingStyle 方法如下所示:(dataTable 是 [String : [String]] 类型的字典,我用它来存储每个单元格的信息,其中键是节标题,值是该节中的单元格。)

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

    if editingStyle == .Delete {

        dataTable[Array(dataTable.keys)[indexPath.section]]!.removeAtIndex(indexPath.row)
        if dataTable[Array(dataTable.keys)[indexPath.section]]!.count == 0 {

            dataTable.removeValueForKey(Array(dataTable.keys)[indexPath.section])
            tableView.deleteSections(NSIndexSet(index: indexPath.section), withRowAnimation: .Fade)

        } else {

            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

        }

    }

}

我相信我已经缩小了问题的范围,但我不知道如何解决它。当我调用 tableView.deleteSections 时,出现错误

'Invalid update: invalid number of rows in section 1.  The number of rows
contained in an existing section after the update (1) must be equal to the
number of rows contained in that section before the update (3), plus or
minus the number of rows inserted or deleted from that section (0 inserted,
0 deleted) and plus or minus the number of rows moved into or out of that
section (0 moved in, 0 moved out).'

我相信这是因为当第 1 部分被删除时,第 2 部分向上移动到第 1 部分,第 3 部分向上移动到第 2 部分,但每个部分中的单元格数量没有更新。在我的测试中,我发现只有在删除的部分之后的每个部分都没有与被删除的部分相同数量的单元格时才会发生此错误(所以 1 个单元格,因为只有当单元格数量减少到零时才会删除该部分).我认为要解决此问题,我可以手动更新每个部分中的单元格数量,但我不知道该怎么做。同样,问题不在于我返回的单元格数和节数不正确。任何帮助都会很棒,在此先感谢。

最佳答案

我找到了我的问题的解决方案,所以我想分享它。出于某种原因,我假设 dataTable 在删除对象后会保持其顺序,所以每次在我的代码中调用 dataTable.keys 时,我都会执行 dataTable.keys.sort().

关于ios - 如何在 Swift 中从 UITableView 中删除部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35098220/

相关文章:

swift - UITableView 的 reloadData 在完成功能中不起作用

queryForTable 之后 Swift reloadTableView

objective-c - UITableViewCell 中的 UIImage

ios - 在 Swift 3.0 iOS 10 中保存和加载时遇到问题

ios - UIView 高度未调整为 UITableView header 中的 subview 高度

ios - textViewDidChangeSelection 方法认为 textView.text 为空

swift - 上传多部分表单数据时如何观察上传进度?

ios - iPhone SDK_表格 View 里面的表格 View

ios - iPhone 5 和 5s 上的 NSHTTPURLResponse 不同

ios - iOS7中如何根据内容调整UITextField的大小?