I'm loading an HTML string of arbitrary length into a UIWebView
which is then displayed in a UITableViewCell
. I do not want this UIWebView
to scroll independently of the UITableView
so I must resize its height to fit the content.
This UITableViewCell
is also collapsable, not showing the UIWebView
when it's in its collapsed state.
The rub is, how do I know what this height is so that I can have heightForRowAtIndexPath
return a proper value and allow the table to look and scroll correctly?
Here's some example code:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 0)
return 286;
if (indexPath.row == 1) {
if (analysisExpanded)
return analysisWebViewHeight + 39;
else
return 52;
}
if (sourcesExpanded)
return sourcesWebViewHeight + 39;
return 53;
}
Pretty simple. The 39 is the height of some header stuff I have in the cell with the webview.
I am loading the "expanded view" of the cell from a nib, so to get the webview I'm calling viewForTag:
UIWebView* sourcesWebView = (UIWebView*)[cell viewWithTag:1];
[sourcesWebView setBackgroundColor:[UIColor clearColor]];
[sourcesWebView loadHTMLString:placeholder baseURL:[NSURL URLWithString:@"http://example.com/"]];
sourcesWebViewHeight = [[sourcesWebView stringByEvaluatingJavaScriptFromString:@"document.documentElement.scrollHeight"] floatValue];
[sourcesWebView setFrame:CGRectMake(sourcesWebView.frame.origin.x, sourcesWebView.frame.origin.y, sourcesWebView.frame.size.width, sourcesWebViewHeight)];
sourcesWebViewHeight
is an iVar that is updated by the above code in cellForRowAtIndexPath
. If the user taps the cell three times, expand-collapse-expand, and does a little scrolling, eventually it gets the correct height.
I tried "Preloading" the height by using a memory-only UIWebView
object, but that never returned correct numbers for some reason.
The issue was that I was attempting to get the scroll size before the web view had a chance to render it.
After implementing the didFinishLoad delegate method, my original javascript worked fine to get the height.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With