加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ios – 自定义字体在WKWebView Swift中不起作用

发布时间:2020-12-14 17:10:19 所属栏目:百科 来源:网络整理
导读:试图在WKWebView中使用自定义字体,但没有运气. let htmlString = "span style="font-family: 'OpenSans-Bold'; font-size: 30; color: white"(Utils.aboutUsText)/span"webView.loadHTMLString(htmlString,baseURL: nil) 我可以使用HelveticaNeue-Bold并
试图在WKWebView中使用自定义字体,但没有运气.

let htmlString = "<span style="font-family: 'OpenSans-Bold'; font-size: 30; color: white">(Utils.aboutUsText)</span>"
webView.loadHTMLString(htmlString,baseURL: nil)

我可以使用HelveticaNeue-Bold并且效果很好,但不能使用上面的自定义字体.

let htmlString = "<span style="font-family: 'HelveticaNeue'; font-size: 30; color: white">(Utils.aboutUsText)</span>"
webView.loadHTMLString(htmlString,baseURL: nil)

我已正确添加自定义字体.查看截图.

有人可以告诉我如何实现这一目标或指出我正确的方向.

enter image description here

enter image description here

enter image description here

解决方法

在DonMag的评论中阅读 the linked thread中的答案:

>使用@ font-face是必需的
>您需要多个@ font-face声明才能将多个字体文件用作单个字体系列
>您需要提供baseURL以使url(OpenSans-Regular.ttf)之类的相对URL工作

所以,试试这个:

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文件:

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)

开放式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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读