简体   繁体   中英

Resizing UIWebview's frame when changing its font size

I have a UIWebview I'd like to change the font size. To do that, I simply use javascript :

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

The problem is that when I set the font size to 50%, there is a big blank area below the content of the uiwebview.

I tried to resize my webview to the height that fit the actual content size by running the following js but it always returns the height of the 100% text, not the 50% and actual one:

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);

---- logs ------

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

I also tried to use document.documentElement.scrollHeight instead of document.body.offsetHeight but this doesn't work either.

Can anyone help me? Thanks.

edit: Here is how I load the html to the webview:

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

Did you try to change the UIWebView scrollerView contentsize instead changing the body size?

Is something like this

 t_webview.scrollView.contentSize=CGSizeMake(width, height); 

I am not sure if this applies to UIWebView. But in iOS, all controls (as far as i know) gets their height property set before setting the content.

That being said, I would try to resize the font before setting the content inside the webview OR I would render the webview as how you are doing it and then when the webview gets properly created, then get the instance of it to resize the height.

Also another question arise if whether you want to keep the size of the UIWebView the same while changing the content size within? (If so, use the answer by @jcesar). However, if you are looking to change the size of the UIWebView then you will need to change the webview size

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM