Custom Font Not Working in WKWebView Swift
Reading the answers in the linked thread in DonMag's comment:
Using
@font-face
is mandatoryYou need multiple
@font-face
declarations to use multiple font files as a single font familyYou need to provide
baseURL
to make relative urls likeurl(OpenSans-Regular.ttf)
work
So, try this:
let htmlString = """
<style>
@font-face
{
font-family: 'Open Sans';
font-weight: normal;
src: url(OpenSans-Regular.ttf);
}
@font-face
{
font-family: 'Open Sans';
font-weight: bold;
src: url(OpenSans-Bold.ttf);
}
@font-face
{
font-family: 'Open Sans';
font-weight: 900;
src: url(OpenSans-ExtraBold.ttf);
}
@font-face
{
font-family: 'Open Sans';
font-weight: 200;
src: url(OpenSans-Light.ttf);
}
@font-face
{
font-family: 'Open Sans';
font-weight: 500;
src: url(OpenSans-Semibold.ttf);
}
</style>
<span style="font-family: 'Open Sans'; font-weight: bold; font-size: 30; color: red">(Utils.aboutUsText)</span>
"""
webView.loadHTMLString(htmlString, baseURL: Bundle.main.bundleURL) //<-
Or you can use a separate css file if you prefer:
let htmlString = """
<link rel="stylesheet" type="text/css" href="open-sans.css">
<span style="font-family: 'Open Sans'; font-weight: bold; font-size: 30; color: red">(Utils.aboutUsText)</span>
"""
webView.loadHTMLString(htmlString, baseURL: Bundle.main.bundleURL)
open-sans.css:
@font-face
{
font-family: 'Open Sans';
font-weight: normal;
src: url(OpenSans-Regular.ttf);
}
@font-face
{
font-family: 'Open Sans';
font-weight: bold;
src: url(OpenSans-Bold.ttf);
}
@font-face
{
font-family: 'Open Sans';
font-weight: 900;
src: url(OpenSans-ExtraBold.ttf);
}
@font-face
{
font-family: 'Open Sans';
font-weight: 200;
src: url(OpenSans-Light.ttf);
}
@font-face
{
font-family: 'Open Sans';
font-weight: 500;
src: url(OpenSans-Semibold.ttf);
}