How to determine UIWebView height based on content, within a variable height UITableView?

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.

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);
}

Leave a Comment