gpt4 book ai didi

ios - 有没有办法更新单个 UITableViewCell 的高度,而无需重新计算每个单元格的高度?

转载 作者:IT老高 更新时间:2023-10-28 11:38:40 25 4
gpt4 key购买 nike

我有一个包含几个不同部分的 UITableView。一个部分包含将随着用户在 UITextView 中键入文本而调整大小的单元格。另一部分包含呈现 HTML 内容的单元格,计算高度的成本相对较高。

现在当用户输入 UITextView 时,为了让表格 View 更新单元格的高度,我调用

[self.tableView beginUpdates];
[self.tableView endUpdates];

但是,这会导致表格重新计算表格中每个单元格的高度,而我实际上只需要更新输入的单个单元格。不仅如此,它不是使用 tableView:estimatedHeightForRowAtIndexPath: 重新计算估计高度,而是为每个单元格调用 tableView:heightForRowAtIndexPath:,即使是那些没有显示的单元格。

有没有办法让表格 View 只更新单个单元格的高度,而不做所有这些不必要的工作?

更新

我仍在寻找解决方案。正如建议的那样,我尝试使用 reloadRowsAtIndexPaths:,但看起来这不起作用。即使只有一行调用 reloadRowsAtIndexPaths: 仍然会导致为每一行调用 heightForRowAtIndexPath:,即使 cellForRowAtIndexPath: 只会被调用您请求的行。事实上,每次插入、删除或重新加载一行时,都会为表格单元格中的每一行调用 heightForRowAtIndexPath:

我还尝试将代码放入 willDisplayCell:forRowAtIndexPath: 以计算单元格即将出现之前的高度。为了使它起作用,我需要在计算后强制表格 View 重新请求行的高度。不幸的是,调用 [self.tableView beginUpdates]; [self.tableView endUpdates]; from willDisplayCell:forRowAtIndexPath: 导致 UITableView 内部代码深处出现索引越界异常。我猜他们不希望我们这样做。

我不禁觉得这是 SDK 中的一个错误,即响应 [self.tableView endUpdates] 它不会为单元格调用 estimatedHeightForRowAtIndexPath:那是不可见的,但我仍在尝试找到某种解决方法。任何帮助表示赞赏。

最佳答案

如前所述,reloadRowsAtIndexPaths:withRowAnimation: 只会导致表格 View 向其 UITableViewDataSource 询问新的单元格 View ,但不会询问 UITableViewDelegate 更新单元格高度。

不幸的是高度只能通过调用来刷新:

[tableView beginUpdates];
[tableView endUpdates];

即使两次调用之间没有任何变化。

如果您计算高度的算法过于耗时,那么您应该缓存这些值。比如:

- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGFloat height = [self cachedHeightForIndexPath:indexPath];

// Not cached ?
if (height < 0)
{
height = [self heightForIndexPath:indexPath];
[self setCachedHeight:height
forIndexPath:indexPath];
}

return height;
}

并确保在内容更改或初始化时将这些高度重置为 -1

编辑:

此外,如果您想尽可能延迟高度计算(直到它们被滚动到),您应该尝试实现这个(仅限 iOS 7+):

@property (nonatomic) CGFloat estimatedRowHeight

Providing a nonnegative estimate of the height of rows can improve the performance of loading the table view. If the table contains variable height rows, it might be expensive to calculate all their heights when the table loads. Using estimation allows you to defer some of the cost of geometry calculation from load time to scrolling time.

The default value is 0, which means there is no estimate.

关于ios - 有没有办法更新单个 UITableViewCell 的高度,而无需重新计算每个单元格的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19374699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com