【问题标题】:How to set custom fonts in WebView(react-native-webview) in iOS?如何在 iOS 的 WebView(react-native-webview) 中设置自定义字体?
【发布时间】:2020-07-11 23:57:26
【问题描述】:

我想在 Webview 中设置自定义字体。我已经实现了以下代码:

@font-face {
    font-family: 'Poppins-Bold'; 
    src:url('file:///android_asset/fonts/Poppins-Bold.ttf') format('truetype')
}
body{
    font-family: Poppins-Bold
    margin: 0;
    padding: 0;
    color: red;
}

它在 android 中运行良好,但在 iOS 中却无法运行。让我知道是否有人对此有解决方案。

注意:我不想使用 google 的 CSS 字体

【问题讨论】:

  • immodi 你解决了这个问题吗?我遇到了同样的问题
  • @German,对不起,伙计,我找不到任何解决方案。

标签: ios react-native react-native-webview


【解决方案1】:
  1. 根据平台设置以下字体 URL:
    const fontUrl = Platform.select({
        ios: "Poppins-Bold.ttf",
        android: "file:///android_asset/fonts/Poppins-Bold.ttf",
    });
    
  2. 将您的 CSS 样式更新为以下内容:
     const css = `
         @font-face {
            font-family: 'Poppins-Bold'; 
            src: local('Poppins-Bold') url('${fontUrl}') format('truetype')
         }
         body {
            font-family: Poppins-Bold
            margin: 0;
            padding: 0;
            color: red;
         }`
    
    • 请注意,使用format('truetype'),因为您的字体扩展名是ttf。如果您使用的是eot 字体,则需要使用format('opentype')
  3. 完成此操作后,使用以下道具更新您的WebView 组件:
    <WebView 
        source={{ html, baseUrl: '' }}
        originWhitelist={["*"]}
    />
    
    • baseUrl 设置为空白将确保加载字体。参考this发帖。
    • 如果不设置originWhitelist,在iOS 上会出现找不到URL 的错误。

这对我在 Android 和 iOS 上都有效,而且我碰巧也在使用 Poppins ?

【讨论】:

  • 感谢更新。我会检查这个解决方案。我认为您的代码有意义。
猜你喜欢
  • 2016-08-15
  • 2022-07-13
  • 2018-02-24
  • 1970-01-01
  • 1970-01-01
  • 2018-08-22
  • 2017-08-14
  • 2018-01-27
  • 1970-01-01
相关资源
最近更新 更多