Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIWebView resize font automatically to best fit page

Is there a way to resize font automatically in a UIWebView so it will look best on screen? Something that will try to set the font size to be in the ideal size for viewing (assuming resizing the text will just wrap the text and not corrupt the whole page).

like image 360
bashan Avatar asked Jan 15 '23 19:01

bashan


2 Answers

I had the same problem, this workaround worked for me:

-(void)webViewDidFinishLoad:(UIWebView *)webView{
[webView scalesPageToFit];
float scale = 130000/webView.scrollView.frame.size.width;
NSString *jsString = [[NSString alloc] initWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%f%%'", scale];
[webView stringByEvaluatingJavaScriptFromString:jsString];
}

I have several UIWebViews of different widths. I want to keep zooming enabled, so scalePageToFit is switched on, which results in tiny text for the UIWebviews of smaller width and large font for UIWebviews of a larger width. To standardise the font size, calculate the scale by dividing some factor (you'll have to adjust this yourself, 130000 worked for me with CSS font size 10pt) by the webview width.

As far as I can tell it's not related to zoomFactor, which is always 1.0. I haven't checked if the fonts are exactly the same size (visually) across the UIWebViews, but good enough for me not to be able to tell.

like image 142
Johnny Rockex Avatar answered Jan 30 '23 15:01

Johnny Rockex


You should set the scalesPageToFit property to YES

You can read the documentation Here

like image 43
Adam Johnson Avatar answered Jan 30 '23 17:01

Adam Johnson