Ossama Hassan
Ossama Hassan

Reputation: 21

Adding custom font to WKWebView is not working

I am trying to use a custom font in a WKWebView but it's not working.

htmlString = """
<head>
<style type=\"text/css\">
@font-face
{
font-family: 'Aljazeera';
font-weight: normal;
src: url(Al-Jazeera-Arabic-Regular.ttf);
}
body{
font-family: 'Aljazeera';
text-align:right;
}
</style>
</head>
<body>\(textFile)</body></html>
""";

webView.loadHTMLString(htmlString, baseURL: nil)

The text-align:right; is working fine so I know it's reading the css. The font is working with UILabels and UIButtons so the app can read it fine.

Upvotes: 1

Views: 2300

Answers (1)

Gowri K
Gowri K

Reputation: 55

Make sure all font files are added in Info.plist and also in project target. FontFile.css file implements font family and the source of the file.

FontFile.css file includes:

@font-face
{
    font-family: 'MonotypeSabonW04-Regular';
    src: local('MonotypeSabonW04-Regular'),url('Monotype Sabon Regular.otf') format('opentype');
}
@font-face
{
    font-family: 'MonotypeSabonW04-Italic';
    src: local('MonotypeSabonW04-Italic'),url('Monotype Sabon Italic.otf') format('opentype');
}

@font-face
{
    font-family: 'CharlotteSansW02-Book';
    src: local('CharlotteSansW02-Book'),url('Charlotte Sans Book.otf') format('opentype');
}


h1
{
    font-family: 'MonotypeSabonW04-Regular';
    font-size: 70px;
    font-weight: normal;
}

h2
{
    font-family: 'MonotypeSabonW04-Italic';
    font-size: 65px;
    font-weight: normal;
}

h3
{
    font-family: 'CharlotteSansW02-Book';
    font-size: 60px;
    font-weight: normal;
}

ViewController.swift file -> In viewDidLoad call below function after setting up WKWebview:

func loadHtmlStringToWKWebView() {
    let strCssHead = """
        <head>\
        <link rel="stylesheet" type="text/css" href="iPhone.css">\
        </head>
        """
    let strBody = """
        <body>\
        <h1>Header Font 1</h1>\
        <h2>Header Font 2</h2>\
        <h3>Header Font 3</h3>\
        </body>
        """

    wkWebView?.loadHTMLString("\(strCssHead)\(strBody)", baseURL: URL(fileURLWithPath: Bundle.main.path(forResource: "FontFile", ofType: "css") ?? ""))
}

Upvotes: 1

Related Questions