【发布时间】: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 为什么不直接调用
beginUpdates和endUpdates,因为这会调用heightForRowAtIndexPath?
标签: ios objective-c uitableview uiwebview