I am attempting to use a UIWebView to display some variable-size content, and I'd like to determine the full size of that content so that I can resize the UIWebView to fit the size of the content perfectly.
My attempts at determining the correct height and width of the content, however, haven't been completely straightforward. The following attempt at testing methods for finding the size...
- (void)viewDidLoad {
[super viewDidLoad];
self.webView.backgroundColor = [UIColor clearColor];
NSString *content = @"<html><body style='background-color: transparent; width: 300px; height: 500px'><div id='ContentDiv'>Content Here</div></body></html>";
[self.webView loadHTMLString:content baseURL:nil];
debugLog(@"Loading HTML string: %@", content);
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *bodyHeight = [self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"];
NSString *bodyWidth = [self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetWidth"];
NSString *contentHeight = [self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('ContentDiv').offsetHeight"];
NSString *contentWidth = [self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('ContentDiv').offsetWidth"];
CGSize fittedSize = [self.webView sizeThatFits:CGSizeZero];
debugLog(@"document.body.offsetHeight/Width: {%@, %@}", bodyWidth, bodyHeight);
debugLog(@"document.getElementbyId('ContentDiv').offsetHeight/Width: {%@, %@}", contentWidth, contentHeight);
debugLog(@"sizeThatFits: %@", NSStringFromCGSize(fittedSize));
self.webView.frame = CGRectMake(0,
0,
[contentWidth floatValue],
[contentHeight floatValue]);
}
...produces the following log results...
Loading HTML string: <html><body style='background-color: transparent; width: 300px; height: 500px'><div id='ContentDiv'>Content Here</div></body></html>
document.body.offsetHeight/Width: {300, 500}
document.getElementbyId('ContentDiv').offsetHeight/Width: {300, 20}
sizeThatFits: {308, 516}
While the first and second results make sense to me - the body size matches the size in the style attribute, and the div size fits the actual content - the third result does not make sense. Indeed, UIWebView seems to inset the actual HTML content by 8 pixels on some edges (top, bottom, and left in this case, it seems) such that the fitted size given by sizeThatFits: doesn't match up with the Javascript body height/width result.
Can anyone give an explanation for this, and potentially a way to eliminate these insets? Thanks.