我想在WKWebView
中使用自定义字体。
我使用insertCSSString(into webView: WKWebView)
,但是一旦将"@font-face{font-family: 'Roboto-BlackItalic'; url('Roboto-BlackItalic.ttf') format('truetype');}"
添加到字符串中,css似乎就不会被评估(在此示例中,任何文本的颜色都不会变为红色)。
该方法取自#pragma comment
所以问题是-如何使用这种方法使用自定义字体。我尝试了以下方法:
extension DetailViewController {
func insertCSSString(into webView: WKWebView) {
let cssString = "@font-face{font-family: 'Roboto-BlackItalic'; url('Roboto-BlackItalic.ttf') format('truetype');} body { font-size: 20px; color: red; background-color: clear; } htesttwo {color: black; }"
let jsString = "var style = document.createElement('style'); style.innerHTML = '\(cssString)'; document.head.appendChild(style);"
webView.evaluateJavaScript(jsString, completionHandler: nil)
}
}
答案 0 :(得分:0)
您应该在创建一个css文件之后将字体放入您的项目中,并在其中放置字体图标
Viewport Rect
将字体文件放到css文件夹中并加载跟随样本
@font-face
{
font-family: 'MonotypeSabonW04-Regular';
src: local('MonotypeSabonW04-Regular'),url('Monotype Sabon Regular.otf') format('opentype');
}
@font-face
{
font-family: 'MonotypeSabonW04-Italic';
src: local('MonotypeSabonW04-Italic'),url('Monotype Sabon Italic.otf') format('opentype');
}
@font-face
{
font-family: 'CharlotteSansW02-Book';
src: local('CharlotteSansW02-Book'),url('Charlotte Sans Book.otf') format('opentype');
}
h1
{
font-family: 'MonotypeSabonW04-Regular';
font-size: 70px;
font-weight: normal;
}
h2
{
font-family: 'MonotypeSabonW04-Italic';
font-size: 65px;
font-weight: normal;
}
h3
{
font-family: 'CharlotteSansW02-Book';
font-size: 60px;
font-weight: normal;
}