Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change WKWebView or UIWebView default font

What font does UIWebView and WKWebView use by default? I would like to be able to change that. But I don't want to do it in the html string, instead I want to have something like:

// obj-c
[webView setFont:[UIFont fontWithName:@"GothamRounded-Bold" size:14]

// swift
webView.setFont(UIFont(name: "GothamRounded-Bold", size: 14))

is there such property or some other way?

like image 870
Au Ris Avatar asked Sep 21 '12 15:09

Au Ris


4 Answers

You can use your UIFont object (so you can set it and modify more easily), but wrap the HTML in a span instead; font tags have been deprecated since HTML 4.01.

UIFont *font = [UIFont fontWithName:@"GothamRounded-Bold" size:14];

Assuming you already have the NSString *htmlString created, you can use the font's properties:

htmlString = [NSString stringWithFormat:@"<span style=\"font-family: %@; font-size: %i\">%@</span>",
                                        font.fontName,
                                        (int) font.pointSize,
                                        htmlString];

Alternatively, you could just supply the values instead of using a UIFont object:

htmlString = [NSString stringWithFormat:@"<span style=\"font-family: %@; font-size: %i\">%@</span>",
                                        @"GothamRounded-Bold",
                                        14,
                                        htmlString];
like image 90
jterry Avatar answered Oct 17 '22 11:10

jterry


Just prefix a <font face> tag to your string before loading into the webView.

NSString *body = [plist objectForKey:@"foo"];
NSString *htmlString = 
    [NSString stringWithFormat:@"<font face='GothamRounded-Bold' size='3'>%@", body];
[webView loadHTMLString:htmlString baseURL:nil];
like image 40
TijuanaKez Avatar answered Oct 17 '22 12:10

TijuanaKez


You could try to set the font by injecting a line of JavaScript like this:

[webView stringByEvaluatingJavaScriptFromString: @"document.body.style.fontFamily = 'GothamRounded-Bold'"];
like image 20
William Niu Avatar answered Oct 17 '22 12:10

William Niu


There is the swift 3 solution :

func webViewDidFinishLoad(_ webView: UIWebView) {
    webView.stringByEvaluatingJavaScript(from: "document.getElementsByTagName('body')[0].style.fontFamily =\"-apple-system\"")
}

I have just put the default iOS font for this example

like image 13
Kevin ABRIOUX Avatar answered Oct 17 '22 12:10

Kevin ABRIOUX