How to delete the last row of a section?(如何删除一个部分的最后一行?)
问题描述
这个问题让我在过去的几个小时里一直很忙.我有两个部分,每个部分有一排.当我删除其中一个部分中的行时,它会抛出一个异常,指出这是一个无效的更新(更新之前和之后的行/部分的数量不一样).这是可以理解的,因为我删除了一个部分的最后一行,因此我删除了该部分.问题是如何避免异常.
This problem has kept me busy for the last hours. I have two sections with one row in each section. When I delete the row in one of the sections than it throws an exception saying this is an invalid update (number of rows/sections before and after the update are not the same). This is understandable as I delete the last row of a section and I therefore delete the section. The question is how to avoid the exception.
我的数据源一切正常.我检查并重新检查(相信我).
Everything is okay with my data source. I checked and rechecked (believe me).
那么,正如线程的标题所述,如何在不出现异常的情况下删除节的最后一行?
So, as the title of the thread states, how do you delete the last row of a section without getting an exception?
谢谢,
巴特
推荐答案
当你删除了一行,并且这一行是其section的最后一个,你需要同时删除这个section.基本上,您需要跟踪要删除的与行关联的 indexPaths 以及与需要删除的部分相关的索引,因为它们不再包含行.你可以这样做:
When you delete a row, and this row is the last one of its section, you need to also delete the section. Basically, you need to keep track of both the indexPaths you want to delete, which are associated to the rows, and the indexes related to the sections that needs to be removed because they no longer contain rows. You could do it as follows:
NSMutableIndexSet *indexes = [NSMutableIndexSet indexSet];
每次从模型数组中删除与 tableView 的特定部分相关的对象时,检查数组计数是否为零,在这种情况下,将表示该部分的索引添加到索引:
Each time you delete an object from your model array related to a specific section of the tableView, check if the array count is zero, in which case add an index representing the section to indexes:
[array removeObjectAtIndex:indexPath.row];
if(![array count])
[indexes addIndex: indexPath.section];
确定所有与要删除的行相关的indexPath,然后更新tableView如下:
Determine all of the indexPaths related to the rows to be deleted, then update the tableView as follows:
[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
[tableView deleteSections:indexes withRowAnimation:UITableViewRowAnimationFade];
[tableView endUpdates];
这对我和我建议该方法的其他人都有效.
This worked for me and other people I suggested the approach.
这篇关于如何删除一个部分的最后一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何删除一个部分的最后一行?
基础教程推荐
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01