編輯于2019-02-20.
注意:只適用于webview加載本地HTML
1.webview 使用自定義字體
css文件 中 :
body{
font-family:#fontfamily#,sans-serif;
}
其中#fontfamily# 替換為字體名字 即可.
- wkwebview 使用自定義字體
同上,會發(fā)現(xiàn)不起作用,修改為以下方式
@font-face
{
font-family: #fontfamily#;
src: local(#fontfamily#),url('http://localhost/CustomFont/#fontfamilyurl#') format('opentype');
}
fontfamily# 和 #fontfamilyurl# 是需要替換的,另外就是資源加載的這個路徑問題,很明顯我這里是把字體放在了沙盒之中,如果要使用項目中存在的字體,路徑直接這么填
@font-face
{
font-family: 'CharlotteSansW02-Book';
src: local('CharlotteSansW02-Book'),url('Charlotte Sans Book.otf') format('opentype');
}
參考上方的##對號入座即可.
要是訪問沙盒中的字體就按上邊的來,這里存在一個問題,假如html代碼是加載的本地文件,代碼是這樣寫的:
NSString * path = [[NSBundle mainBundle] resourcePath];
NSURL * baseURL = [NSURL fileURLWithPath:path];
[self.webView loadHTMLString:HtmlString baseURL:baseURL];
常規(guī)方法設置會訪問不到沙盒中的文件,這有個教程:
http://www.reibang.com/p/be83c57bbf67 (本地開了一個類似Apache服務器),即可解決
參考 : https://stackoverflow.com/questions/25785179/using-custom-fonts-in-wkwebview
附上一 demo : https://github.com/AdityaDeshmane/iOSWKWebViewCustomFontDemo,可以參考下