如何确定UIWebView的高度基于内容,在一个变量高度UITableView? [英] How to determine UIWebView height based on content, within a variable height UITableView?
问题描述
我试图创建一个 UITableView
变量高度行,如解答这个问题
I am trying to create a UITableView
with variable height rows as explained in the answer to this question
我遇到的问题是每个单元格包含与不同(静态加载)内容的 UIWebView
我不知道如何根据内容计算适当的高度。有办法做到这一点吗?我试过这样的东西:
My problem is each cell contains a UIWebView
with different (statically loaded) content I can't figure out how to calculate the proper height based on the content. Is there a way to do this? I've tried things like this:
(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
WebViewCell *cell = (WebViewCell*)[self tableView:tableView cellForRowAtIndexPath:indexPath];
[cell setNeedsLayout];
[cell layoutIfNeeded];
return cell.bounds.size.height;
}
单元格本身是从nib加载的,这只是一个 UITableViewCell
包含 UIWebView
。 (如果单元格只是调整到最大的html内容,尽管变量的高度会更好)。
The cells themselves are loaded from a nib, which is simply a UITableViewCell
containing a UIWebView
. (It would also be fine if the cells just adjusted themselves to the largest of the html content, though variable height would be nicer).
推荐答案
这个代码对于表视图使用可能太慢了,但是它的技巧。它看起来没有任何替代方法,因为UIWebView不能直接访问DOM。
This code is probably too slow for table view use, but does the trick. It doesn't look like there's any alternative, as UIWebView offers no direct access to the DOM.
在视图控制器的 viewDidLoad
我在webview中加载一些HTML,当加载完成后,运行一些javascript来返回元素高度。
In a view controller's viewDidLoad
I load some HTML in a webview and when the load is finished run some javascript to return the element height.
- (void)viewDidLoad
{
[super viewDidLoad];
webview.delegate = self;
[webview loadHTMLString:@"<div id='foo' style='background: red'>The quick brown fox jumped over the lazy dog.</div>" baseURL:nil];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *output = [webview stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"foo\").offsetHeight;"];
NSLog(@"height: %@", output);
}
这篇关于如何确定UIWebView的高度基于内容,在一个变量高度UITableView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!