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

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

问题描述

这个问题让我在最后几个小时都很忙。我有两个部分,每个部分中有一行。当我删除一个部分中的行,而不是抛出一个异常,说这是一个无效的更新(更新前后的行数/部分不一样)。这是可以理解的,因为我删除一个部分的最后一行,因此我删除该部分。问题是如何避免异常。



我的数据源一切正常。



因此,作为线程的标题,如何删除一个段的最后一行而不会引起异常? / p>

感谢,



Bart

解决方案

删除一行时,该行是其最后一行,您还需要删除该部分。基本上,您需要跟踪要删除的indexPath(与这些行相关联)以及与由于不再包含行而需要删除的节相关的索引。您可以这样做:

  NSMutableIndexSet * indexes = [NSMutableIndexSet indexSet]; 

每次从与tableView的特定部分相关的模型数组中删除一个对象时,数组计数为零,在这种情况下,向索引添加表示段的索引:

  [array removeObjectAtIndex:indexPath.row] ; 
if(![array count])
[indexes addIndex:indexPath.section];

确定与要删除的行相关的所有indexPath,然后按如下所示更新tableView: / p>

  [tableView beginUpdates]; 
[tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
[tableView deleteSections:indexes withRowAnimation:UITableViewRowAnimationFade];
[tableView endUpdates];

这适合我和其他人我建议的方法。


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?

Thanks,

Bart

解决方案

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];

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];

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天全站免登陆