iOS Swift - TableView 删除行错误

标签 ios uitableview

错误: '无效更新:第 0 节中的行数无效。更新 (1) 后现有节中包含的行数必须等于更新 (1) 前该节中包含的行数,加上或减去从该部分插入或删除的行数(0 插入,1 删除)加上或减去移入或移出该部分的行数(0 移入,0 移出)。'

看了很多相关的帖子,还是找不到答案。

以下是相关代码片段(不包含全部代码):

var todoItems : [Assignment] = []
var sections = Dictionary<String, Array<Assignment>>()
var sortedSections = [String]()

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == UITableViewCellEditingStyle.Delete {
        var tableSection = sections[sortedSections[indexPath.section]]
        tableSection!.removeAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
    }

}


override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return sortedSections[section]
}

override func viewDidLoad() {
    super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return sections.count
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return sections[sortedSections[section]]!.count
}

感谢您的帮助!

最佳答案

您删除了数组中的元素,但错过了包含部分的字典更新:(

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == UITableViewCellEditingStyle.Delete {
        var tableSection = sections[sortedSections[indexPath.section]]
        tableSection!.removeAtIndex(indexPath.row)

        //add this line
        sections[sortedSections[indexPath.section]] = tableSection

        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}

关于iOS Swift - TableView 删除行错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34823930/

相关文章:

iphone - 如何让 UITableViewCell 的 subview 扩展到单元格的边界之外

ios - 使用 NSPredicate 比较两个数组并返回重复的字符

ios - 分组表中的 TableView 页眉/页脚字体(Swift)

ios - 是否可以在 Xcode 中将 "Debug View Hierarchy"用于应用程序扩展?

ios - 使 UITabBarItem 项目之一在 UITabBarController 中没有 View

ios - UIViewController 子类也会影响我的 UITableViewControllers 吗?

iphone - 不同部分的自定义分组 UITable 标题

ios - 同一屏幕上包含两个表格 View 的 ScrollView 限制垂直滚动

ios - 当我的自定义 TableView 单元格中的用户选项卡调用按钮时,如何从 json 获取号码并在拨号盘中显示该号码

ios - 如何获取对/更新一个自定义 UITableview 标题 View 的引用?