我從插入和刪除UITableViewCells的同一個UITableView有很多痛苦!插入和刪除UITableViewCell同時不能正常工作
我通常不張貼代碼,但我認爲這是表示在我遇到問題的最好辦法:
- (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段, 1st(從0開始索引)和5行。當您選擇一個部分時 - 它會刪除您之前選擇的部分中的行,並將行添加到您剛選擇的部分。
Pictorally,當我加載應用程序,我有這樣的事情:
的形象在這裏:http://www.freeimagehosting.net/uploads/1b9f2d57e7.png
選擇部分2的錶行0之後,我再刪除第1部分的行(默認選中)並添加第2部分的行。但是,我得到這個:
圖片在這裏:http://www.freeimagehosting.net/uploads/6d5d904e84.png
......這不是我期望發生的!看起來第2部分的第一行似乎仍然存在 - 即使它最初被刪除。
如果我只是做一個[tableView reloadData],一切顯示爲正常...但我顯然forefit好的動畫。
我真的很感激,如果有人能在這裏發光!這讓我有點瘋狂!
再次感謝, 尼克。
嘿eJames,感謝您的評論 - 一個真正有效的點!我想了一會,它可能解決我的問題 - 但我仍然有同樣的麻煩。我認爲實際上可能會有iPhone,但是當您嘗試從一個部分移除項目並同時將其添加到另一個部分時... – 2008-12-01 22:01:21