Estoy intentando usar un UIWebView para mostrar contenido de tamaño variable, y me gustaría determinar el tamaño completo de ese contenido para poder cambiar el tamaño del UIWebView para que se ajuste perfectamente al tamaño del contenido.¿Por qué - [UIWebView sizeThatFits:] da un tamaño mayor que document.body.offsetHeight/Width?
Sin embargo, mis intentos de determinar la altura y el ancho correctos del contenido no han sido completamente sencillos. El siguiente intento de métodos de prueba para encontrar el tamaño ...
- (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]);
}
... produce los siguientes resultados del registro ...
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}
Mientras que el primer y segundo resultados tienen sentido para mí - la el tamaño del cuerpo coincide con el tamaño en el atributo de estilo, y el tamaño del div se ajusta al contenido real; el tercer resultado no tiene sentido. De hecho, UIWebView parece incluir el contenido HTML real en 8 píxeles en algunos bordes (arriba, abajo, y a la izquierda en este caso, parece) de modo que el tamaño ajustado dado por sizeThatFits: no coincide con la altura del cuerpo de Javascript/resultado de ancho
¿Alguien puede dar una explicación para esto, y potencialmente una forma de eliminar estas inserciones? Gracias.
Por supuesto, una respuesta tan simple, gracias por la pronta respuesta. –