自定义字体在WKWebView Swift中不起作用 [英] Custom Font Not Working in WKWebView Swift
问题描述
尝试在WKWebView中使用自定义字体,但是没有运气.
Trying to use custom font in WKWebView but no luck.
let htmlString = "<span style=\"font-family: 'OpenSans-Bold'; font-size: 30; color: white\">\(Utils.aboutUsText)</span>"
webView.loadHTMLString(htmlString, baseURL: nil)
我可以使用HelveticaNeue-Bold,并且效果很好,但不能与上面的自定义字体一起使用.
I can use HelveticaNeue-Bold and works great but not with the custom font above.
let htmlString = "<span style=\"font-family: 'HelveticaNeue'; font-size: 30; color: white\">\(Utils.aboutUsText)</span>"
webView.loadHTMLString(htmlString, baseURL: nil)
我已经正确添加了自定义字体.请参见屏幕截图.
I have added the custom fonts properly.See screenshots.
有人可以告诉我如何实现这一目标或为我指明正确的方向.
Can someone please tell me how can i achieve this or point me in the right direction.
推荐答案
在DonMag的链接的线程中阅读答案评论:
Reading the answers in the linked thread in DonMag's comment:
-
强制使用
@font-face
您需要多个@font-face
声明才能将多个字体文件用作单个字体系列
You need multiple @font-face
declarations to use multiple font files as a single font family
您需要提供baseURL
才能使类似url(OpenSans-Regular.ttf)
的相对网址正常工作
You need to provide baseURL
to make relative urls like url(OpenSans-Regular.ttf)
work
因此,请尝试以下操作:
So, try this:
let htmlString = """
<style>
@font-face
{
font-family: 'Open Sans';
font-weight: normal;
src: url(OpenSans-Regular.ttf);
}
@font-face
{
font-family: 'Open Sans';
font-weight: bold;
src: url(OpenSans-Bold.ttf);
}
@font-face
{
font-family: 'Open Sans';
font-weight: 900;
src: url(OpenSans-ExtraBold.ttf);
}
@font-face
{
font-family: 'Open Sans';
font-weight: 200;
src: url(OpenSans-Light.ttf);
}
@font-face
{
font-family: 'Open Sans';
font-weight: 500;
src: url(OpenSans-Semibold.ttf);
}
</style>
<span style="font-family: 'Open Sans'; font-weight: bold; font-size: 30; color: red">(Utils.aboutUsText)</span>
"""
webView.loadHTMLString(htmlString, baseURL: Bundle.main.bundleURL) //<-
或者,如果您愿意,也可以使用单独的CSS文件:
Or you can use a separate css file if you prefer:
let htmlString = """
<link rel="stylesheet" type="text/css" href="open-sans.css">
<span style="font-family: 'Open Sans'; font-weight: bold; font-size: 30; color: red">(Utils.aboutUsText)</span>
"""
webView.loadHTMLString(htmlString, baseURL: Bundle.main.bundleURL)
open-sans.css:
open-sans.css:
@font-face
{
font-family: 'Open Sans';
font-weight: normal;
src: url(OpenSans-Regular.ttf);
}
@font-face
{
font-family: 'Open Sans';
font-weight: bold;
src: url(OpenSans-Bold.ttf);
}
@font-face
{
font-family: 'Open Sans';
font-weight: 900;
src: url(OpenSans-ExtraBold.ttf);
}
@font-face
{
font-family: 'Open Sans';
font-weight: 200;
src: url(OpenSans-Light.ttf);
}
@font-face
{
font-family: 'Open Sans';
font-weight: 500;
src: url(OpenSans-Semibold.ttf);
}
这篇关于自定义字体在WKWebView Swift中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!