同じ 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 つのセクションを作成し、1 番目 (0 からインデックス付け) は 5 行で構成されます。セクションを選択すると、以前に選択したセクションから行が削除され、選択したセクションに行が追加されます。
図的に、アプリをロードすると、次のようになります。
画像はこちら: http://www.freeimagehosting.net/uploads/1b9f2d57e7.png
セクション 2 のテーブル行 0 を選択した後、セクション 1 (デフォルトで選択されています) の行を削除し、セクション 2 の行を追加します。しかし、次のようになります。
画像はこちら: http://www.freeimagehosting.net/uploads/6d5d904e84.png
...これは私が期待するものではありません! セクション 2 の最初の行は、確実に削除されますが、何とか残っているようです。
[tableView reloadData]を実行すると、すべてが正常に表示されます...しかし、私は明らかに素晴らしいアニメーションを忘れています。
誰かがここに光を当てることができれば、本当に感謝しています!それは私を少し夢中にさせています!
ありがとう、ニック。