1

I want to use custom fonts in a WKWebView.

I use insertCSSString(into webView: WKWebView), but as soon as I add "@font-face{font-family: 'Roboto-BlackItalic'; url('Roboto-BlackItalic.ttf') format('truetype');}" to the string the css appears not not be evaluated (in this example the colour of any text does not change to red).

The approach is taken from Using custom fonts in WKWebView

So the question is - how can I use custom fonts with this approach. I have tried the following:

extension DetailViewController {
    func insertCSSString(into webView: WKWebView) {
        let cssString = "@font-face{font-family: 'Roboto-BlackItalic'; url('Roboto-BlackItalic.ttf') format('truetype');} body { font-size: 20px; color: red; background-color: clear; } htesttwo {color: black; }"
        let jsString = "var style = document.createElement('style'); style.innerHTML = '\(cssString)'; document.head.appendChild(style);"
        webView.evaluateJavaScript(jsString, completionHandler: nil)
    }
}
Ashish
  • 579
  • 7
  • 20
stevenpcurtis
  • 1,803
  • 2
  • 19
  • 42
  • 1
    where is your font file ? is it on your device? , because fontface run from the server that you have your html code there and you use the fontface in your app, so you have to have the font file on your device – mohsen Aug 27 '19 at 11:36
  • Yes, the fonts are on the device. – stevenpcurtis Aug 28 '19 at 02:03

1 Answers1

0

you should just put your fonts into your project after that create a css file and put the fontface code there like that

@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;
}

after put the fonts file on the css folder and load it with followfing sample

let strCssHead = "<head><link rel=\"stylesheet\" type=\"text/css\" href=\"iPhone.css\"></head>"
let strbody = "<body> <h1>Font 1</h1> <h2>Font 2</h2> <h3>Font 3</h3> </body>"
        wkweb.loadHTMLString("\(strCssHead)\(strbody)", baseURL: URL(fileURLWithPath: Bundle.main.path(forResource: "iPhone", ofType: "css")!))
mohsen
  • 3,895
  • 1
  • 27
  • 45
  • @stevenpcurtis Here is a sample for you : https://medium.com/if-let-swift-programming/css-in-your-xcode-project-2b7011a29cb3 – mohsen Sep 24 '19 at 07:48