【问题标题】:How to get rid of unwanted whitespace when collapsing TableViewCell折叠 TableViewCell 时如何摆脱不需要的空白
【发布时间】:2018-09-24 22:53:13
【问题描述】:

我有一个 UITableView,当用户点击它们时,单元格会展开/折叠,使用:

-(void)tableView:(UITableView *)_tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  ...
  [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
  ...
}

运行 reloadRowsAtIndexPath 后,我让 heightForRowAtIndexPath 返回不同的高度,具体取决于单元格是折叠还是展开:

-(CGFloat)tableView:(UITableView *)_tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  // if expand
  return 200;
  // if collapse
  return 49;
}

当我折叠表格底部的单元格时,表格会缩小,但它会被拉得太远,在表格顶部留下大量空白。在调用reloadRowsAtIndexPaths 之后,我尝试了[tableView scrollToRowAtIndexPath:indexPath],这解决了问题,但是这让桌子跳动了。它会下降太多,留下空白然后跳回顶部。如何在不向下滚动太多的情况下缩小表格单元格?

【问题讨论】:

    标签: ios objective-c uitableview


    【解决方案1】:

    更改影响 tableView 高度的内容后,您可以使用这些代码更新单元格高度而无需重新加载表格:

    [tableView beginUpdates];
    [tableView endUpdates];
    

    【讨论】:

    • 我尝试在调用 reloadRowsAtIndexPath 之前和之后调用这两个函数,但它们似乎没有任何区别。我认为这是因为 reloadRowsAtIndexPath 启动了一个新线程,并且 [tableView endUpdates] 在线程完成之前运行。还是我做错了什么?
    • 在使用这些方法时不要重新加载行。
    • 我刚刚再次查看了文档,似乎 beginUpdates 和 endUpdates 只需要在插入/删除行时调用。改变单元格高度不需要它们。
    • 是的,但是当您的表格行发生更改以使表格视图立即呈现时,它也可以工作。
    【解决方案2】:

    也许你可以在主线程中使用UIView 动画来避免这种情况,例如:

    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.3 animations:^{
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }];
    });
    

    那就试试吧:

    if (@available(iOS 11.0, *)) {
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
    }
    

    【讨论】:

    • 我尝试在[tableView reloadRowsAtIndexPaths] 之后调用它,但在折叠单元格后它仍然跳动
    • @TienPhan 编辑了我的答案。请看一下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 2015-01-08
    • 1970-01-01
    相关资源
    最近更新 更多