0

Im a new in IOS. And i want to change font in WebView.

My webView page loading like this:

// contentRendered - cames from API like html

   self?.webView.loadHTMLString(contentRendered, baseURL: nil)

I have code for change font:

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

    let font = UIFont.init(name: "Quicksand-Regular", size: 22)
    let jsFont = "document.getElementsByTagName('body')[0].style.fontFamily = '\(font!)';"
    webView.evaluateJavaScript(jsFont, completionHandler: nil)
}

But it doesnt work. Quicksand-Regular i have in resources folder

UPD:

let jsFont = "document.getElementsByTagName('body')[0].style.fontFamily = 'Quicksand-Regular';"
webView.evaluateJavaScript(jsFont, completionHandler: nil)

Doesnt work too

  • Is it also listed in your `Info.plist`? (https://developer.apple.com/documentation/uikit/text_display_and_fonts/adding_a_custom_font_to_your_app) – jnpdx Jul 08 '21 at 09:17
  • @jnpdx yes, i have added the font to Info.plist. The font `Quicksand-Regular ` works well for UILabel but not for webView – xivosij786 Jul 08 '21 at 09:18
  • Is there a reason you're passing the `UIFont` object into the string for interpolation rather than just using the font name? I'm guessing that's creating a funny looking string. – jnpdx Jul 08 '21 at 09:19
  • @jnpdx i tried many ways to change the font. Tried to write `let jsFont = "document.getElementsByTagName('body')[0].style.fontFamily = 'Quicksand-Regular';"` but it doesnt work too – xivosij786 Jul 08 '21 at 09:24
  • Have you looked at this? https://stackoverflow.com/questions/25785179/using-custom-fonts-in-wkwebview – jnpdx Jul 08 '21 at 09:25
  • @jnpdx the value `contentRendered`(wich came form API) contains the html like this: `text for a test

    Text p

    ,

    Title

    ` there may be a problem due to the fact that the text does not contain the full html tags(body, etc)?
    – xivosij786 Jul 08 '21 at 09:26
  • @jnpdx thanks for the link, i saw this, but let me try again – xivosij786 Jul 08 '21 at 09:27
  • I doubt it's the tags. I'd bet it's the fact that (according to the answers I linked to), the CSS declarations have to be pretty specific to get custom fonts to load. – jnpdx Jul 08 '21 at 09:28
  • Take a look at this answer [here](https://stackoverflow.com/a/63294541/8314394). It might give you a hint on how to modify your HTML and also how to load local font + pay attention at the `baseURL` usage. Can you post your HTML and maybe I can give you an exact answer how to add it. – Starsky Jul 08 '21 at 10:26

1 Answers1

7

To apply a custom font to an external HTML loaded in WKWebView (forced) Use the WKWebView HTML in the app if you want to display a custom font was added to the app in the CSS as shown below can be referred to (likely).

@font-face {

  font-family: 'CustomFontFamily';

  src: url('CustomFontFile.otf') format('opentype');
 }
============================================

import UIKit
 import WebKit

class ViewController: UIViewController, WKNavigationDelegate {



    @IBOutlet weak var webView: WKWebView!



    override func viewDidLoad() {

        super.viewDidLoad()

        webView.navigationDelegate = self



        let url = URL(string: "https://example.com/")

        let request = URLRequest(url: url!)

        webView.load(request)

    }



    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {

        //to encode the font data in the app in the Base64 

        let yuGothicMedium = getDataString(otf: "YuGothic-Medium")

        let yuGothicBold = getDataString(otf: "YuGothic-Bold")



        //embedded encoded font data in the Data URI scheme CSS 

        let cssString = """

        @font-face {

            font-family: 'YuGothic';

            src: url('data:font/otf;base64,\(yuGothicMedium)') format('opentype');

            font-weight: normal;

        }

        @font-face {

            font-family: 'YuGothic';

            src: url('data:font/otf;base64,\(yuGothicBold)') format('opentype');

            font-weight: bold;

        }

        """



        //JavaScript to add the CSS as a style element 

        because//cssString is to enter a new line template literal 

        let customFontJs = """

        var style = document.createElement('style');

        style.innerHTML = `\(cssString)`;

        document.head.appendChild(style);

        """



        //executes the JavaScript 

        webView.evaluateJavaScript(customFontJs, completionHandler: nil)

    }



    func getDataString(otf: String) -> String {

        let path = Bundle.main.path(forResource: otf, ofType: "otf")

        let url = URL(fileURLWithPath: path!)

        let data = try! Data(contentsOf: url)

        return data.base64EncodedString()

    }
 }
Noman Umar
  • 369
  • 1
  • 7