从同一个 UITableView 插入和删除 UITableViewCells 时,我感到非常痛苦!
我通常不发布代码,但我认为这是显示问题所在的最佳方式:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 5;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (iSelectedSection == section) return 5;
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//NSLog(@"drawing row:%d section:%d", [indexPath row], [indexPath section]);
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
if (iSelectedSection == [indexPath section]) {
cell.textColor = [UIColor redColor];
} else {
cell.textColor = [UIColor blackColor];
}
cell.text = [NSString stringWithFormat:@"Section: %d Row: %d", [indexPath section], [indexPath row]];
// Set up the cell
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic -- create and push a new view controller
if ([indexPath row] == 0) {
NSMutableArray *rowsToRemove = [NSMutableArray array];
NSMutableArray *rowsToAdd = [NSMutableArray array];
for(int i=0; i<5; i++) {
//NSLog(@"Adding row:%d section:%d ", i, [indexPath section]);
//NSLog(@"Removing row:%d section:%d ", i, iSelectedSection);
[rowsToAdd addObject:[NSIndexPath indexPathForRow:i inSection:[indexPath section]]];
[rowsToRemove addObject:[NSIndexPath indexPathForRow:i inSection:iSelectedSection]];
}
iSelectedSection = [indexPath section];
[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:rowsToRemove withRowAnimation:YES];
[tableView insertRowsAtIndexPaths:rowsToAdd withRowAnimation:YES];
[tableView endUpdates];
}
}
此代码创建 5 个部分,第一个(从 0 开始索引)有 5 行。当您选择一个部分时 - 它会从您之前选择的部分中删除行,并将行添加到您刚刚选择的部分。
如图所示,当我加载应用程序时,我有这样的东西:
图片在这里:http ://www.freeimagehosting.net/uploads/1b9f2d57e7.png
选择第 2 节的表第 0 行后,我删除第 1 节的行(默认选中)并添加第 2 节的行。但我得到了:
图片在这里:http ://www.freeimagehosting.net/uploads/6d5d904e84.png
...这不是我期望发生的!似乎第 2 节的第一行以某种方式保留了 - 即使它肯定被删除了。
如果我只是做一个 [tableView reloadData],一切都会正常显示......但我显然会放弃漂亮的动画。
如果有人可以在这里发光,我将非常感激!这让我有点发疯!
再次感谢尼克。