html - 向 WKWebView 添加自定义字体不起作用

标签 html ios css swift wkwebview

我正在尝试在 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 文件 -> 在 vi​​ewDidLoad 中设置 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/

相关文章:

javascript - 访问 javascript 字符串变量中特定标签的内容

ios - 如何使自定义过渡表现得像重力下落一样?

javascript - 悬停在按钮/元素上时如何使它们具有动画效果?

css - 覆盖高度属性并禁用它

ios - 想在 View 动画完成后显示一个新 View

CSS :hover function not working

javascript - page speed , yslow 工具是否足以了解网站组织和性能

javascript - Markdown 解析器应该是客户端还是服务器端

jquery - 如何在 jQuery 中获取 CSS 高度值(而不是计算的高度)

javascript - Objective C chop 字符串的最后一部分