假设我有一个 tableView 部分,只有 2 个单元格,用户名和密码。如果我点击其中任何一个单元格,我想在它们正下方添加另一个单元格(包含有关有效用户名的信息等)。一次只能看到一个详细信息单元格,因此如果用户名打开并且我点击密码,用户名一将被删除,密码一将被添加。
我遇到了一个问题,如果用户名是打开的,并且我点击密码,应用程序就会崩溃。它试图在 indexPath.row 3 处插入一个单元格(因为那时,用户名在 0,用户名详细信息在 1,密码在 2。但是,刚刚发生了删除,到那时用户名详细信息消失了,所以它试图在 3 处插入,而实际上它应该在 2 处插入。
我可以在这里做什么?对于本应如此简单的操作,整个单元格更新的事情似乎异常复杂。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSIndexPath *indexPathToDelete = self.controlRowIndexPath;
if ([indexPath isEqual:self.tappedIndexPath]) {
[tableView deselectRowAtIndexPath:indexPath animated:NO];
self.tappedIndexPath = nil;
self.controlRowIndexPath = nil;
if (indexPath.section == 0) self.cellDetailOpenInSection0 = NO;
else if (indexPath.section == 1) self.cellDetailOpenInSection1 = NO;
else self.cellDetailOpenInSection2 = NO;
} else {
self.tappedIndexPath = indexPath;
self.controlRowIndexPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:indexPath.section];
if (indexPath.section == 0) self.cellDetailOpenInSection0 = YES;
else if (indexPath.section == 1) self.cellDetailOpenInSection1 = YES;
else self.cellDetailOpenInSection2 = YES;
}
[self.userPassTableView beginUpdates];
if (indexPathToDelete) {
[self.userPassTableView deleteRowsAtIndexPaths:@[indexPathToDelete] withRowAnimation:UITableViewRowAnimationAutomatic];
if (indexPathToDelete.section == 0) self.cellDetailOpenInSection0 = NO;
else if (indexPathToDelete.section == 1) self.cellDetailOpenInSection1 = NO;
else if (indexPathToDelete.section == 2) self.cellDetailOpenInSection2 = NO;
}
if (self.controlRowIndexPath) {
[self.userPassTableView insertRowsAtIndexPaths:@[self.controlRowIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
if (self.controlRowIndexPath.section == 0) self.cellDetailOpenInSection0 = YES;
else if (self.controlRowIndexPath.section == 1) self.cellDetailOpenInSection1 = YES;
else if (self.controlRowIndexPath.section == 2) self.cellDetailOpenInSection2 = YES;
}
// Trying to insert one at a location that no longer exists because it just deleted one.
[self.userPassTableView endUpdates];
}