how to increase or decrease the UIWebview font size, not using scalePageToFit:NO;
I have 2 buttons - A- and A+
@interface
NSUInteger textFontSize;
- (IBAction)changeTextFontSize:(id)sender
{
switch ([sender tag]) {
case 1: // A-
textFontSize = (textFontSize > 50) ? textFontSize -5 : textFontSize;
break;
case 2: // A+
textFontSize = (textFontSize < 160) ? textFontSize +5 : textFontSize;
break;
}
NSString *jsString = [[NSString alloc] initWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%d%%'",
textFontSize];
[web stringByEvaluatingJavaScriptFromString:jsString];
[jsString release];
}
in my case im using a UISlider for the fontSize, can be any float value
func webViewDidFinishLoad(_ webView: UIWebView) {
if let fontSize: Float = (self.fontSizeSlider?.value) {
webView.stringByEvaluatingJavaScript(from: "document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '\(fontSize)%%'")
print(fontSize)
}
}
Here is mine for changing font size and color in UIWebView:
NSString *myString=@"Hello World!";
int textFontSize=2;
NSString *myHTML=[NSString stringWithFormat: @"<html><body><script>var str = '%@'; document.write(str.fontsize(%d).fontcolor('green'));</script></body></html>",myString,textFontSize];
[myWebView loadHTMLString:myHTML baseURL:nil];
Try the below code :
NSString *setTextSizeRule = [NSString stringWithFormat:@"addCSSRule('body', '-webkit-text-size-adjust: %d%%;')",currentTextSize];
[_webview stringByEvaluatingJavaScriptFromString:setTextSizeRule];
There is currently no exposed way to directly manipulate the DOM in a UIWebView, nor any convenience methods for handling things like font sizes. I suggest filing Radars.
Having said that. you can modify the font size by changing the CSS, like any other webpage. If that is not possible (you don't control the content) you can write a small javascript function to change the CSS properties in the pages DOM, and execute it by calling:
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;
Swift 5 Update. This is an updated answer from @BLCs suggestion.
Also fixes the double %% in his string.
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
let textSize = 300
let javascript = "document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '\(textSize)%'"
webView.evaluateJavaScript(javascript) { (response, error) in
print()
}
}