调整UIWebview的大小'更改其字体大小时的边框

Resizing UIWebview's frame when changing its font size

本文关键字:字体 小时 边框 UIWebview 调整      更新时间:2023-09-26

我有一个UIWebview,我想更改字体大小。要做到这一点,我只需使用javascript:

NSString *jsString = [NSString stringWithFormat:@"document.body.style.webkitTextSizeAdjust= '%d%%'",50];
    [t_webview stringByEvaluatingJavaScriptFromString:jsString];

问题是,当我将字体大小设置为50%时,uiwebview的内容下面有一个很大的空白区域。

我试图通过运行以下js将我的网络视图调整到适合实际内容大小的高度,但它总是返回100%文本的高度,而不是50%和实际文本的高度:

NSLog(@"font size: %i%%",theHeightIWant);
    NSString* t_height = [t_webview stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"];
    NSLog(@"height before: %@",t_height);
    NSString *jsString = [NSString stringWithFormat:@"document.body.style.webkitTextSizeAdjust= '%d%%'",theHeightIWant];
    [t_webview stringByEvaluatingJavaScriptFromString:jsString];
    t_height = [t_webview stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"];
    NSLog(@"height after: %@",t_height);

----日志------

font size: 95%
height before: 932
height after: 932
font size: 90%
height before: 932
height after: 932
font size: 85%
height before: 932
height after: 932

我还尝试使用document.documentElement.scrollHeight而不是document.body.offsetHeight,但这也不起作用。

有人能帮我吗?谢谢

edit:以下是我如何将html加载到webview:

NSString* t_html = [NSString stringWithFormat:@"<html><body>%@</body></html>",t_htmlPharmaco];
    [webview loadHTMLString:t_html baseURL:[[NSBundle mainBundle] bundleURL]];

我不确定这是否适用于UIWebView。但在iOS中,所有控件(据我所知)在设置内容之前都会设置其高度属性。

话虽如此,在设置网络视图内的内容之前,我会尝试调整字体大小,或者我会将网络视图呈现为您正在进行的操作,然后在正确创建网络视图时,获取它的实例以调整高度。

如果您是否希望在更改内容大小的同时保持UIWebView的大小不变,还会出现另一个问题?(如果是,请使用@jcesar的答案)。但是,如果您希望更改UIWebView的大小,则需要更改网络视图大小