【发布时间】:2016-01-08 18:49:56
【问题描述】:
所以我有一个 UITableView,其中包含一个我想在单击按钮时更新的部分。现在,本节中的行数正在使用不同的数组填充。我根据字典中的索引选择返回哪一个。像这样的:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
switch (section) {
case 0:
return 1;
case 1: {
NSMutableArray *array = [self.dict objectForKey:[NSNumber numberWithInteger:self.index]];
return [array count] + 1;
}
default:
break;
}
return 1;
}
因此,第 1 节的行取决于不同的数组。所以现在在我的表格视图中,我有一个按钮,可以在第 1 节中插入另一行,并且我也更新了相应的数组。现在,当我点击更新此部分以显示 self.dict 数据结构中不同数组的值的另一个按钮时,我收到一个错误: '无效更新:第 1 节中的行数无效。更新后现有节中包含的行数 (3) 必须等于更新前该节中包含的行数 (4),加上或减去从该部分插入或删除的行数(0 插入,0 删除)加上或减去移入或移出该部分的行数(0 移入,0 移出)。 因此,例如,如果在我的第一个数组中我有 3 个单元格,然后用户再添加一个单元格,因此有 4 个单元格,那么如果用户单击应该更新第 1 部分以显示第二个数组(有 3 个单元格)的按钮, 上面的错误被抛出。我认为这是因为数据源发生了变化,并且行数减少了,而没有明确删除单元格。我该如何解决这个问题?
更新了更多代码:
// Insert here when the very last cell of section 1 is selected
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSMutableArray *array = [self.dict objectForKey:[NSNumber numberWithInteger:self.index]];
if (indexPath.section == 1 && indexPath.row == [array count]) {
[array addObject:[NSNumber numberWithInt:8]];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:[array count]-1 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
}
}
// Code for reloading the table view
- (IBAction)next:(id)sender {
self.index++;
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];
}
}
【问题讨论】:
-
您能否显示代码,您在哪里添加了一个单元格并在哪里更新了第 1 部分以显示第二个数组?
标签: ios objective-c arrays xcode uitableview