18

Trying to use custom font in WKWebView but no luck.

let htmlString = "<span style=\"font-family: 'OpenSans-Bold'; font-size: 30; color: white\">\(Utils.aboutUsText)</span>"
webView.loadHTMLString(htmlString, baseURL: nil)

I can use HelveticaNeue-Bold and works great but not with the custom font above.

let htmlString = "<span style=\"font-family: 'HelveticaNeue'; font-size: 30; color: white\">\(Utils.aboutUsText)</span>"
webView.loadHTMLString(htmlString, baseURL: nil)

I have added the custom fonts properly.See screenshots.

Can someone please tell me how can i achieve this or point me in the right direction.

enter image description here

enter image description here

enter image description here

iYousafzai
  • 1,021
  • 1
  • 10
  • 29

2 Answers2

44

Reading the answers in the linked thread in DonMag's comment:

  • Using @font-face is mandatory

  • You need multiple @font-face declarations to use multiple font files as a single font family

  • You need to provide baseURL to make relative urls like url(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);
}
OOPer
  • 47,149
  • 6
  • 107
  • 142
  • 10
    Thanks for showing `baseURL: Bundle.main.bundleURL` – onmyway133 Oct 05 '18 at 07:29
  • 3
    I also have some social feeds to our web content. I lose all the social feeds if baseURL is Bundle.main.bundleURL. – harikrista Oct 08 '18 at 19:46
  • Struggled for a long while until figure out about `baseURL: Bundle.main.bundleURL`, thank you very much! – henrique Oct 18 '19 at 21:14
  • Do you know why `src: local(...)` doesn't work but url does? – Harout360 Nov 12 '19 at 23:33
  • 2
    @Harout360, I do not know much about `src: local`, but the core part of `WKWebView` runs in another process (not just another thread, but another process), so fonts embedded in an app bundle might not be considered to be _local_. – OOPer Nov 13 '19 at 11:11
-1
class StaticContentViewControlle:  WKUIDelegate, WKNavigationDelegate {
    @IBOutlet weak var webViewContainer: UIView!
    private var webView: WKWebView?
    var url = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initialSetup()
    }
    
    func initialSetup() {
        url = "https://www.apple.com"
        
        let myURL = URL(string: url)
        if let myURL = myURL {
            let myRequest = URLRequest(url: myURL)
            webView?.uiDelegate = self
            webView?.load(myRequest)
        }
        webView?.navigationDelegate = self
        webView?.scrollView.showsVerticalScrollIndicator = false
        webView?.scrollView.backgroundColor = .clear
        webView?.isOpaque = false
        webView?.backgroundColor = .clear
    }
    
    
    
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        print("Start loading")
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("End loading")
        let textSize = 300
        let javascript = "document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '\(textSize)%'"
        webView.evaluateJavaScript(javascript) { (response, error) in
            print()
        }
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if navigationAction.navigationType == .linkActivated  {
            if let url = navigationAction.request.url,
                UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url)
                decisionHandler(.cancel)
            } else {
                print("Open it locally")
                decisionHandler(.allow)
            }
        } else {
            print("not a user click")
            decisionHandler(.allow)
        }
    }
}
Deviyani Swami
  • 749
  • 8
  • 17