如何删除一个部分的最后一行? [英] How to delete the last row of a section?

查看:23
本文介绍了如何删除一个部分的最后一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题让我在过去的几个小时里一直很忙.我有两个部分,每个部分有一排.当我删除其中一个部分中的行时,它会抛出一个异常,指出这是一个无效的更新(更新之前和之后的行/部分的数量不一样).这是可以理解的,因为我删除了一个部分的最后一行,因此我删除了该部分.问题是如何避免异常.

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.

这篇关于如何删除一个部分的最后一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆