UITableView reloadRowsAtIndexPaths图形故障

时间:2011-09-08 09:20:11

标签: ios uitableview animation visual-glitch

如果我为一个部分的第一个单元格调用reloadRowsAtIndexPaths,前一个部分为空,而上面的部分为空 - 我得到一个奇怪的动画故障(即使我指定“UITableViewRowAnimationNone”),其中重新加载的单元格从以上部分..

我试图尽可能地简化示例:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 0)
    return 1;
else if (section == 1)
    return 0;
else if (section == 2)
    return 3;
return 0;
}

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

// Configure the cell...
cell.textLabel.text =  @"Text";

return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *editedCell = [[NSArray alloc] initWithObjects:indexPath, nil];
//[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:editedCell withRowAnimation:UITableViewRowAnimationNone];
//[self.tableView endUpdates];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return @"Section";
}

实际上你可以注释掉最后一种方法,但它可以更好地理解这个问题。

1 个答案:

答案 0 :(得分:13)

您可以直接设置所需的值,而不是让表重新加载(从而避免任何不需要的动画)。此外,为了使代码更清晰并避免代码重复,可以将单元格设置移动到单独的方法(因此我们可以从不同的位置调用它):

- (void) setupCell:(UITableViewCell*)cell forIndexPath:(NSIndexPath*)indexPath {
   cell.textLabel.text =  @"Text"; // Or any value depending on index path
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

   UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
   [self setupCell:cell forIndexPath:indexPath];
}

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   // create cell

   // Configure the cell...
   [self setupCell:cell forIndexPath:indexPath];

   return cell;
}
相关问题