Nic*_*ght 7 iphone cocoa-touch insert
我在同一个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];
}
}
Run Code Online (Sandbox Code Playgroud)
此代码创建5个部分,第1个(从0索引)有5行.当您选择一个部分时 - 它会从您之前选择的部分中删除行,并将行添加到您刚刚选择的部分.
Pictorally,当我加载应用程序时,我有这样的事情:
图片来源:http://www.freeimagehosting.net/uploads/1b9f2d57e7.png
在选择了第2部分的表格行0之后,然后我删除第1部分的行(默认选中)并添加第2部分的行.但是我得到了这个:
图片来源:http://www.freeimagehosting.net/uploads/6d5d904e84.png
......这不是我期望发生的事情!似乎第2部分的第一行仍以某种方式保留 - 尽管它肯定会被删除.
如果我只是做一个[tableView reloadData],一切看起来都很正常......但我显然适应了漂亮的动画.
如果有人能在这里发光,我真的很感激!这让我有点疯狂!
再次感谢,尼克.
挣扎着让它发挥作用.这是我在tableView中添加一行的代码:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[tableView beginUpdates];
[dataSource insertObject:[artistField text] atIndex:0];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
[tableView endUpdates];
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8191 次 |
最近记录: |