在带有动画的第一行中插入时,UITableView无法正确显示单元格

时间:2012-02-08 13:16:13

标签: ios uitableview animation

我的应用程序有一个UITableViewController作为根控制器和一个模态视图来向该表添加一行。我正在使用CoreData,所以我从NSFetchedResultsController获取数据。无论如何,问题在于管理UITableView。

每次插入都会使TableView添加一个新单元格。除非在第一行添加单元格,否则一切正常。在这种情况下,不显示其内容。单元格显示为空白。如果我点击单元格或者以某种方式滚动表格,必须重新加载单元格,它会显示其内容。

我正在使用动画,所以我做了[tableView beginUpdates]和[tableView endUpdates],正如Apple文档所说,而不是[tableView reloadData]。如果我做[tableView reloadData]一切正常。

我已经检查了它,并为每一行运行相同的代码。这是关于细胞显示方式的问题。

我认为问题是关于TableViews中动画的“理论”,你可能不需要它,但我的UITableViewController中有相关的代码:

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
   Customer *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
   cell.textLabel.text = managedObject.name;
}


#pragma mark - Table view data source

- (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];
   }

   [self configureCell:cell atIndexPath:indexPath];

   return cell;
}


#pragma mark - FetchedResultsController delegate


- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    [self.tableView beginUpdates];
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
   [self.tableView endUpdates];
   // [self.tableView reloadData]; this make all works OK but without animations
}


- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
   atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
  newIndexPath:(NSIndexPath *)newIndexPath {

UITableView *tableView = self.tableView;

switch(type) {

    case NSFetchedResultsChangeInsert:
        [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
        break;

    case NSFetchedResultsChangeDelete:
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        break;

    case NSFetchedResultsChangeUpdate:
        [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
        break;

    case NSFetchedResultsChangeMove:
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade];
        break;
}
}

1 个答案:

答案 0 :(得分:0)

switch语句中针对每种类型的更改,为什么不添加:

[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

您必须根据更改的类型略微改变该代码,但这样就无需beginUpdatesendUpdates