我正在尝试使用UIWebView来显示一些可变大小的内容,并且我想确定该内容的完整大小,以便我可以调整UIWebView的大小以完美适应内容的大小。
然而,我尝试确定内容的正确高度和宽度并不完全简单。以下是测试查找大小方法的尝试...
- (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]);
}
...生成以下日志结果...
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}
虽然第一和第二个结果对我来说很合理——body的大小与style属性中的大小相匹配,div的大小适合实际内容——但第三个结果不合理。事实上,UIWebView似乎在某些边缘(在这种情况下,似乎是顶部、底部和左侧)将实际的HTML内容缩进了8像素,以至于由sizeThatFits:给出的适合大小与Javascript body高度/宽度结果不匹配。
有人能解释一下这是为什么,并可能提供一种消除这些插入的方法吗?谢谢。