【问题标题】:UITableView: How to 'fix' current cell after row insertion?UITableView:如何在行插入后“修复”当前单元格?
【发布时间】:2014-07-17 10:13:54
【问题描述】:

我有一个 UITableView。我想在表格顶部插入一些行。但是在插入之后,旧的单元格被向下推。

NSArray *indexPaths = @[[NSIndexPath indexPathForRow: 0 inSection: 0]];
[self.tableView insertRowsAtIndexPaths: indexPaths withRowAnimation: UITableViewRowAnimationNone];

例如: 插入前:

  • 项目 1
  • 第 2 项
  • 项目 3
  • 第 4 项
  • 第 5 项
  • ...

插入后

  • 项目-5
  • 项目-4
  • 项目-3
  • ...
  • 项目 1
  • 第 2 项
  • ...

我想将第 1 项保持在它的“旧位置”,例如:

插入后

  • 项目 1
  • 第 2 项
  • 项目 3
  • ...

并且新插入的单元格在旧单元格的上方(屏幕上未显示)。

【问题讨论】:

  • 在 UITableView 中设置滚动位置 ... [theTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:savedScrollPosition inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];

标签: ios uitableview


【解决方案1】:

试试下面的,

 [tableView scrollToRowAtIndexPath:value atScrollPosition:UITableViewScrollPositionTop animated:NO];

请注意,该值将是 indexPath,其中行数是您添加的新行数。

要创建 indexPath 使用,

[NSIndexPath indexPathForRow:inSection:]

【讨论】:

  • 它可以解决问题,但不是最好的解决方案。屏幕闪烁几次,用户体验不好。
  • 添加所有行然后滚动到第一行?这样可以确保屏幕只闪烁一次。所以我想这应该不是问题。
【解决方案2】:

我自己解决了这个问题。我认为它更流畅,具有更好的用户体验。

    for (Poi *poi in fetchedObjects) {
        [self.objects insertObject: poi atIndex: 0];
    }

    CGFloat totalHeight = 0;
    for (int i=0; i<fetchedObjects.count; ++i) {
        totalHeight += [self tableView: self.tableView heightForRowAtIndexPath: [NSIndexPath indexPathForRow: i inSection: 0]];
    }

    CGPoint currentContentOffset = self.tableView.contentOffset;
    currentContentOffset.y += totalHeight;
    [self.tableView reloadData];
    self.tableView.contentOffset = currentContentOffset;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多