我试图用一个UIWebView来显示一些可变大小的内容,我想,以确定该内容的全尺寸,这样我可以调整的UIWebView完全适合内容的大小。为什么 - [UIWebView sizeThatFits:]给出的尺寸大于document.body.offsetHeight/Width?
我在确定所述内容的正确的高度和宽度的尝试,但是,并不完全明了。在测试方法发现的大小下面尝试...
- (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}
虽然第一和第二的结果是有意义的我 - 主体大小与style属性中的大小相匹配,div大小适合实际内容 - 第三个结果没有意义。事实上,UIWebView似乎在某些边缘(在这种情况下,顶部,底部和左侧)插入了8个像素的实际HTML内容,这样sizeThatFits:给出的合适大小与Javascript身高/宽度结果。
谁能给这个解释,并有可能的方式来消除这些插图?谢谢。
当然,这样一个简单的答案 - 感谢您的及时答复。 – 2009-11-21 19:44:09