迅速。WebKit 的自定义字体

0 fonts webview swift

我是 IOS 新人。我想更改 WebView 中的字体。

我的 webView 页面加载如下:

// contentRendered - 来自 html 等 API

   self?.webView.loadHTMLString(contentRendered, baseURL: nil)
Run Code Online (Sandbox Code Playgroud)

我有更改字体的代码:

    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)
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用。Quicksand-Regular我在资源文件夹中有

更新:

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

也不起作用

Nom*_*mar 8

将自定义字体应用到 WKWebView 中加载的外部 HTML(强制) 如果要显示在 CSS 中添加到应用程序的自定义字体,请在应用程序中使用 WKWebView HTML,如下所示可以参考(可能)。

@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()

    }
 }
Run Code Online (Sandbox Code Playgroud)