【问题标题】:Setting height for UITableViewCell with UIWebView inside使用 UIWebView 为 UITableViewCell 设置高度
【发布时间】:2017-01-20 12:13:57
【问题描述】:

我的自定义 UITableViewCells 中有一个 UIWebView。问题是我不太清楚如何动态调整 UITableViewCell 单元格的大小,因为单元格内的 webview 需要先渲染,然后我才能知道 webview 的高度。

我提出的解决方案如下:

CustomCell.m 符合UIWebViewDelegate 并在其内部的webview 完成加载后通过委托方法返回自己的高度。

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
    [self.contentWebview setFrameHeight:height];
    [self.delegate cellDidFinishLoadingWithCell:self withHeight:height];
}

然后 TableViewController.m 符合单元格的委托,并通过执行以下操作重绘:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    return [self.heights[[NSString stringWithFormat:@"%i%i",indexPath.section,indexPath.row]] floatValue];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UIWebViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"webview-cell" forIndexPath:indexPath];
    MyData *d = self.data[indexPath.section];
    [cell setUpCellForData:d];
    [cell setDelegate:self];
    return cell;
}

- (void)cellDidFinishLoadingWithCell:(LessonTableViewCell *)cell withHeight:(CGFloat)height {
    NSIndexPath *indexPath = [self.tableview indexPathForCell:cell];
    NSString *key = [NSString stringWithFormat:@"%i%i",indexPath.section,indexPath.row];
    if (!self.heights[key]) {
        [self.heights setObject:[NSNumber numberWithFloat:height] forKey:key];
    }
    [self.tableview beginUpdates];
    [self.tableview endUpdates];
}

有些单元格的高度似乎是正确的,但其中许多最终的高度为 0...

【问题讨论】:

  • @matt 我不确定这是否可行。一方面,调用 reloadData 会导致每个单元格重新渲染其 web 视图。您可以参加快速的 SO 聊天会话吗?我认为在那里解释我的具体情况会比在评论部分中更快。 chat.stackoverflow.com/rooms/123193/webview
  • @matt 为什么不直接调用beginUpdatesendUpdates,因为这会调用heightForRowAtIndexPath

标签: ios objective-c uitableview uiwebview


【解决方案1】:

删除:

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

添加:

[self.tableView reloadData];




这是苹果文档:
beginUpdates
reloadData

https://stackoverflow.com/a/8174094/2530660

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-29
    • 2013-01-01
    • 2015-12-09
    • 2016-05-19
    • 1970-01-01
    • 2015-02-17
    • 2011-06-04
    • 1970-01-01
    相关资源
    最近更新 更多