【发布时间】:2012-01-28 05:48:46
【问题描述】:
这是我在 UITableView 中删除单元格的代码:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView beginUpdates];
if([tableView numberOfRowsInSection:[indexPath section]] > 1) {
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
} else {
[tableView deleteSections:[NSIndexSet indexSetWithIndex:[indexPath section]]
withRowAnimation:UITableViewRowAnimationFade];
}
[tableView endUpdates];
}
在删除单元格之前还有一些数据正在更新,但我很确定它正在正确更新,因为每次删除单元格时,数据源数组的count 总是少一个。这是预期的行为。然而由于某种原因,每当我删除部分中的最后一个单元格时,我都会得到'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (0) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
这非常令人沮丧,尤其是因为从我在 Internet 上能够找到的信息来看,我这样做是正确的。也许我需要睡觉了,已经有一段时间了。这里有什么想法吗?
解决方案:
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
if(tableIsEmpty) {
//**this** line was the culprit- returning zero here fixed the problem
return 0;
} else if(section == ([tableView numberOfSections] - 1)) {
//this is the last section- it only needs one row for the 'Delete all' button
return 1;
} else {
//figure out how many rows are needed for the section
}
}
【问题讨论】:
标签: ios uitableview delete-row