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

试图在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);
}

相关文章

在有效期内的苹果开发者账号(类型为个人或者公司账号)。还...
Appuploader官网--IOS ipa上传发布工具,证书制作工具跨平台...
苹果在9月13号凌晨(北京时间)发布 iOS 16,该系统的设备可...
计算机图形学--OpenGL递归实现光线追踪
Xcode 14打出来的包在低版本系统运行时会崩溃,报错信息是Li...