WKWebView加载本地字体

合理的设计都千篇一律,奇葩的需求各有各的不同。

从URL加载页面,加载完成后,修改页面字体:

  1. 将字体文件.otf.ttf加入工程;
  2. 在Info.plist文件中加入Fonts provided by application数组,添加字体文件;
  3. 列出将要使用的字体;
for familyName in UIFont.familyNames {
    let fontNames = UIFont.fontNames(forFamilyName: familyName)
    debugPrint("\(familyName):::\(fontNames)")
}
  1. 更改WKWebView字体。
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        let fontFamily = "字体集名称"
        if let fontUrl = Bundle.main.url(forResource: "字体文件名", withExtension: "字体扩展名") {
        do {
                let fontData = try Data(contentsOf: fontUrl, options: .mappedIfSafe)
                let fontEncoding = fontData.base64EncodedString()
                
                let scriptFormat = "var fontcss = '@font-face { font-family: \"%@\"; src: url(data:font/ttf;base64,%@) format(\"truetype\");} *{font-family: \"%@\" !important;}';var head = document.getElementsByTagName('head')[0],style = document.createElement('style');style.type = 'text/css';style.innerHTML = fontcss;head.appendChild(style);"

                let fontScript = String(format: scriptFormat, fontFamily, fontEncoding, fontFamily)
                webView.evaluateJavaScript(fontScript, completionHandler: nil)
            } catch {
                debugPrint("\(self.debugDescription) ===> 获取字体文件出错")
            }
        } else {
            debugPrint("\(self.debugDescription) ===> 字体文件不存在")
        }
    }

⚠️ 注意:此方法存在性能问题,let fontEncoding = fontData.base64EncodedString()在字体文件较大的情况下会严重影响性能!

✅ 若从本地加载htmlString,请参考stackoverflow

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。