ios - 重新加载 UITableView 数据而不重新定位 UITableViewCells

标签 ios layout uitableview nsfetchedresultscontroller

我有一个从 NSFetchedResultsController 接收数据的 UITableView。 NSFetchedResultsController 的数据偶尔会被网络调用更新。每次通过网络调用更新数据后,我都会使用 [tableView reloadData] 更新 UITableView 以添加任何新项目。

我的部分 UI 还使单元格可以水平重新定位。我希望每次刷新表的数据时不要重新定位这些单元格,但不幸的是,[tableview reloadData] 就是这样做的。

在不重新定位行的情况下更新 TableView 中的数据的理想方法是什么?我应该覆盖 tableview 的 reloadData 方法并在那里做一些花哨的事情,或者可能覆盖 tableview 单元格 layoutSubviews 方法吗?

我像这样定位单元格:

CGRect newFrame = cell.frame;
newFrame.origin.x = -cell.frame.size.width;
cell.frame = newFrame;

在 NSFetched 结果 Controller 从网络调用中接收到更多数据后,它会调用它的委托(delegate)方法:
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
    [self.eventTableView reloadData];
}

调用 tableview: cellForRowAtIndexPath: 并且从出队返回的单元格的原点位于 (0,0)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath    *)indexPath
{
    static NSString *CellIdentifier = @"EventCell";
    EventCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        [cellNib instantiateWithOwner:self options:nil];
        cell = self.customCell;
    }

    // Configure the cell...
    Event *event = [fetchedResultsController objectAtIndexPath:indexPath];
    [cell configureCellWithEvent:event];

    return cell;
}

最佳答案

你可以试试 UITableViewDelegate 方法 tableView:willDisplayCell:forRowAtIndexPath: ,在将任何单元格添加到表格 View 或滚动到表格的可见区域之前调用它。在那里,您可以根据需要定位单元格,这将在重新加载后起作用。

这对您的问题并不重要,但我还建议更改单元格的变换属性而不是其框架。这样一来,您就不会意外地将其移动得比您想要的更远(例如,如果您将其移动两次)。

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
  //Determine if the cell should be shifted.
  if (cellShouldShift) {
     cell.transform = CGAffineTransformMakeTranslation(0 - cell.bounds.size.width, 0);
  } else {
     cell.transform = CGAffineTransformIdentity;
  }
}

关于ios - 重新加载 UITableView 数据而不重新定位 UITableViewCells,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11676725/

相关文章:

ios - 取消正在进行的 CloudKit 查询

ios - 为什么我使用框架得到不可用的声明

Java GUI 创建 JTables 表的最佳方法?

html - 这个简单的 HTML、CSS 布局有什么问题?

ios - 在 UITableView 中设置自定义标题 View

ios - 即使应用程序未在后台运行,如何使 iOS 应用程序执行一些代码?

Android TableLayout vs GridView vs 其他?

objective-c - 使用数组传递数据但在 TableView 委托(delegate)中显示为空

ios - UITableView 重新加载数据后出现 NSInternalInconsistencyException

objective-c - 使用 stringWithContentsOfFile : 读取文件时出现问题