【发布时间】:2014-02-05 05:18:45
【问题描述】:
我在尝试删除 UITableView 中的一行时遇到了一些奇怪的行为。
我的应用中有两个表格视图,它们在 tableView:commitEditingStyle:forRowAtIndexPath: 方法上的代码几乎相同。一个工作正常,另一个有这个问题:假设我的表格视图上有超过 X 行,我不知道,所以单元格重用和滚动都启用了。如果我删除列表顶部的一行,则显示在屏幕底部的单元格在点击删除按钮之前都被底部单元格复制。因此,例如,如果我删除 5 行,我的 tableview 上将有相同的单元格。然后,如果我滚动表格视图,它们都会恢复正常。 (或者如果我更改 viewcontroller 然后回到 tableview 的那个)
这是工作表视图的代码:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
if (search.text.length == 0) {
[tableArray removeObjectAtIndex:indexPath.row];
[goalTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self setBG];
tempArray = [NSArray arrayWithArray:tableArray];
[[NSUserDefaults standardUserDefaults]setObject:tempArray forKey:@"currentArray"];
totalGoals = [[NSUserDefaults standardUserDefaults] integerForKey:@"totalGoals"];
totalGoals = totalGoals - 1;
[[NSUserDefaults standardUserDefaults] setInteger:totalGoals forKey:@"totalGoals"];
[[NSUserDefaults standardUserDefaults] synchronize];
} } }
这是有缺陷的tableview的代码:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
if (search.text.length == 0) {
[tableArray removeObjectAtIndex:indexPath.row];
[goalTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self setBG];
tempArray = [NSArray arrayWithArray:tableArray];
[[NSUserDefaults standardUserDefaults]setObject:tempArray forKey:@"completedArray"];
completedGoals = [[NSUserDefaults standardUserDefaults] integerForKey:@"completedGoals"];
completedGoals = completedGoals - 1;
[[NSUserDefaults standardUserDefaults] setInteger:completedGoals forKey:@"completedGoals"];
[[NSUserDefaults standardUserDefaults] synchronize];
} } }
嗯,它几乎是一样的,所以我有点迷失在这里 - 他们有相同的代码,一个工作正常,另一个不是。 cellForRowAtIndexPath: 方法可能有问题吗?我想知道,但在这种方法上找不到任何东西,而且它们实际上也是一样的。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString * identifier = @"Cell";
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell==nil) {
//here I'm setting up the cells, labels, and stuff.
}
if (search.text.length == 0 && [filteredArray count] == 0) {
NSDictionary * dict = [tableArray objectAtIndex:[tableArray count] - 1 - indexPath.row];
//here I use the values on the dict to do some stuff with labels, etc.
}
return cell;
}
问题是,我正在用这一行“翻转”数组:
NSDictionary * dict = [tableArray objectAtIndex:[tableArray count] - 1 - indexPath.row];
如果我不这样做,也就是说,当我只做[tableArray objectAtIndex:indexPath.row] 这样的事情时,删除问题根本不会发生!这是由于反转数组而发生的事情。
哦,顺便提一下,当我填充单元格时(例如,当视图正在加载时),单元格重用工作得很好,没有重复的单元格或类似的东西。只有在删除行时才会发生这种情况。
【问题讨论】:
标签: ios iphone uitableview row-removal