31

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?

Anton Tropashko
  • 5,486
  • 5
  • 41
  • 66
Au Ris
  • 4,541
  • 2
  • 26
  • 53

10 Answers10

48

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];
jterry
  • 6,209
  • 2
  • 30
  • 36
  • 1
    Great method, one important thing to note: This is rendered prior to displaying content unlike the javascript method. – Chris J Jun 27 '13 at 17:33
  • One disadvantage of this approach is, declaring `UIFont` uses some RAM, which can be avoided by just providing the font name and size in string and integer. – Raptor May 10 '14 at 16:26
  • This suffers from the same issue I mentioned on TijuanaKez's answer. In short it's hackish and breaks the HTML of the pages you are displaying. – devios1 Mar 18 '15 at 23:11
23

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];
abbood
  • 23,101
  • 16
  • 132
  • 246
TijuanaKez
  • 1,472
  • 3
  • 20
  • 28
  • 4
    *sidenote:* it works, but font tag is already deprecated long time ago, as suggested by other answer. In short, DO NOT USE `` tag – Raptor May 10 '14 at 16:24
  • 3
    This is also just a horrible solution in general, as you're guaranteed to break the HTML. You're going to be wrapping the and tags in an outer tag, which is just horrible. Even if it *happens* to work because browsers are tolerant enough, that doesn't excuse this kind of design, imo. – devios1 Mar 18 '15 at 23:10
20

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

[webView stringByEvaluatingJavaScriptFromString: @"document.body.style.fontFamily = 'GothamRounded-Bold'"];
William Niu
  • 15,798
  • 7
  • 53
  • 93
  • For font size: [webView stringByEvaluatingJavaScriptFromString: @"document.getElementsByTagName('body')[0].style.fontSize = '15px'"]; – Chris J Jun 27 '13 at 17:31
  • Make sure you call the above script _after_ loading the web content, e.g. from the delegate's webViewDidFinishLoad method. – pipacs Sep 07 '15 at 14:28
13

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

Kevin ABRIOUX
  • 16,507
  • 12
  • 93
  • 99
8

Here is my easy-to-use and easy-to-expand solution with more font settings:

myHTMLLabel = [[UIWebView alloc] initWithFrame:CGRectMake(myX, myY, myWidth, myHeight)];

myHTMLLabel.userInteractionEnabled=NO;
myHTMLLabel.scalesPageToFit=NO;

[myHTMLLabel setOpaque:NO];
myHTMLLabel.backgroundColor = myBackColor;

NSString *myHTMLText = [NSString stringWithFormat:@"<html>"
                        "<head><style type='text/css'>"
                        ".main_text {"
                        "   display: block;"
                        "   font-family:[fontName];"
                        "   text-decoration:none;"
                        "   font-size:[fontSize]px;"
                        "   color:[fontColor];"
                        "   line-height: [fontSize]px;"
                        "   font-weight:normal;"
                        "   text-align:[textAlign];"
                        "}"
                        "</style></head>"
                        "<body> <SPAN class='main_text'>[text]</SPAN></body></html>"];

myHTMLText = [myHTMLText stringByReplacingOccurrencesOfString: @"[text]" withString: myText];
myHTMLText = [myHTMLText stringByReplacingOccurrencesOfString: @"[fontName]" withString: myFontName];
myHTMLText = [myHTMLText stringByReplacingOccurrencesOfString: @"[fontSize]" withString: myFontSize];
myHTMLText = [myHTMLText stringByReplacingOccurrencesOfString: @"[fontColor]" withString: myFontColorHex];
myHTMLText = [myHTMLText stringByReplacingOccurrencesOfString: @"[textAlign]" withString: myFontAlign];


NSLog(@"*** renderHTMLText --> myHTMLText: %@",myHTMLText);

[myHTMLLabel loadHTMLString:myHTMLText baseURL:nil];
Stonz2
  • 6,306
  • 4
  • 44
  • 64
Al-Noor Ladhani
  • 2,413
  • 1
  • 22
  • 14
7

In case someone is looking for a solution in Swift 3, I used this (based on jterry's answer):

let font = UIFont.init(name: "Name-of-your-font", size: theSize)
self.newsWebView.loadHTMLString("<span style=\"font-family: \(font!.fontName); font-size: \(font!.pointSize); color: #21367B\">\(yourString)</span>", baseURL: nil)

Be aware that here I'm not making sure the font isn't nil. A nil check could be added before loading the HTML string. Here I'm also changing the color of the font by adding the color option in the style of the span. This is completely optional.

Iris
  • 291
  • 5
  • 10
5

Quick solution for SWIFT 4.2

    let fontName =  "PFHandbookPro-Regular"
    let fontSize = 20
    let fontSetting = "<span style=\"font-family: \(fontName);font-size: \(fontSize)\"</span>"
    webView.loadHTMLString( fontSetting + myHTMLString, baseURL: nil)

span is an inline element, meaning that it can be on a line with other elements

Jack
  • 13,571
  • 6
  • 76
  • 98
4
@Environment(\.dynamicTypeSize) var dynamicTypeSize

....

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
{
     webView.evaluateJavaScript("document.getElementsByTagName('body')[0].style.fontFamily =\"-apple-system\"")
    // year 2022 resolution: respect accessibility settings. Dynamic Type has been around for EONS: "just use it"
    
    switch dynamicTypeSize {
    case .xSmall:
         // copy code from unknown default clause and adjust to each case of simply lazily fallthrough
        ...
    case .small:
        ...
    case .medium:
        ...
    case .large:
        ...
    case .xLarge:
        ...
    case .xxLarge:
        ...
    case .xxxLarge:
        ...
    case .accessibility1:
        ...
    case .accessibility2:
        ...
    case .accessibility3:
        ...
    case .accessibility4:
        ...
    case .accessibility5:
        ...
    @unknown default:
         webView.evaluateJavaScript("document.getElementsByTagName('body')[0].style.fontSize = \"xx-large\"")

}

wrapping in span tag had zero effect in wkwebview

Anton Tropashko
  • 5,486
  • 5
  • 41
  • 66
3

UIWebview uses the font that's set in the HTML. There is not 'default font'. Even if no font is specifically mentioned, you do not have access to set it. It's all inside the WebKit, which we don't have access to.

Ravi
  • 7,929
  • 6
  • 38
  • 48
  • Hmm, too bad. It would be handy to have a setFont property like it is in UITextView. – Au Ris Sep 21 '12 at 15:30
  • 7
    There is a default font. All web browsers have a default font that is used when no font is otherwise specified. Whether it is customizable or not is the question, and it seems the answer is no. – devios1 Mar 18 '15 at 23:12
3

For Swift, I use this one in webViewDidFinishLoad

webView.stringByEvaluatingJavaScriptFromString("document.getElementsByTagName('body')[0].style.fontFamily =\"HelveticaNeue\"");
alitosuner
  • 984
  • 1
  • 10
  • 15