我试图使用UIWebView显示一些可变大小的内容,我想确定该内容的完整大小,以便我可以调整UIWebView的大小以完全适合内容的大小.
然而,我尝试确定内容的正确高度和宽度并非完全直截了当.以下尝试测试查找尺寸的方法......
- (void)viewDidLoad { [super viewDidLoad]; self.webView.backgroundColor = [UIColor clearColor]; NSString *content = @"Content Here"; [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:Content Heredocument.body.offsetHeight/Width: {300, 500} document.getElementbyId('ContentDiv').offsetHeight/Width: {300, 20} sizeThatFits: {308, 516}
虽然第一和第二个结果对我有意义 - 体型大小与style属性中的大小相匹配,而div大小与实际内容相符 - 第三个结果没有意义.实际上,UIWebView似乎在某些边缘(在这种情况下,顶部,底部和左侧)上插入了8个像素的实际HTML内容,使得sizeThatFits:给出的拟合尺寸与Javascript体高度不匹配/宽度结果.
任何人都可以对此作出解释,并可能是消除这些插入的方法吗?谢谢.