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.
这篇关于如何删除一个部分的最后一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何删除一个部分的最后一行?
基础教程推荐
- 如何从 logcat 中删除旧数据? 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
