我正在尝试在 WKWebView 中使用自定义字体,但它不起作用。
htmlString = """
<head>
<style type=\"text/css\">
@font-face
{
font-family: 'Aljazeera';
font-weight: normal;
src: url(Al-Jazeera-Arabic-Regular.ttf);
}
body{
font-family: 'Aljazeera';
text-align:right;
}
</style>
</head>
<body>\(textFile)</body></html>
""";
webView.loadHTMLString(htmlString, baseURL: nil)
文本对齐:右;工作正常,所以我知道它正在读取 CSS。 该字体与 UILabels 和 UIButtons 配合使用,因此应用程序可以很好地读取它。
最佳答案
确保所有字体文件都添加到 Info.plist 和元素目标中。 FontFile.css 文件实现字体系列和文件源。
FontFile.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;
}
ViewController.swift 文件 -> 在 viewDidLoad 中设置 WKWebview 后调用下面的函数:
func loadHtmlStringToWKWebView() {
let strCssHead = """
<head>\
<link rel="stylesheet" type="text/css" href="iPhone.css">\
</head>
"""
let strBody = """
<body>\
<h1>Header Font 1</h1>\
<h2>Header Font 2</h2>\
<h3>Header Font 3</h3>\
</body>
"""
wkWebView?.loadHTMLString("\(strCssHead)\(strBody)", baseURL: URL(fileURLWithPath: Bundle.main.path(forResource: "FontFile", ofType: "css") ?? ""))
}
关于html - 向 WKWebView 添加自定义字体不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57582426/