【问题标题】:Adding custom font to WKWebView is not working向 WKWebView 添加自定义字体不起作用
【发布时间】:2019-08-20 22:49:20
【问题描述】:

我正在尝试在 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)

text-align:right;工作正常,所以我知道它正在读取 CSS。 该字体与 UILabels 和 UIButtons 一起使用,因此应用程序可以正常阅读。

【问题讨论】:

  • 这将是您的 src 网址。尝试字体文件 src 的文件路径:url("file://getpathtofontfile/Al-Jazeera-Arabic-Regular.ttf")

标签: html ios css swift wkwebview


【解决方案1】:

确保所有字体文件都添加到 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 文件 -> 设置 WKWebview 后在 viewDidLoad 调用下面的函数:

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") ?? ""))
}

【讨论】:

    猜你喜欢
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-22
    相关资源
    最近更新 更多