我試圖用一個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