如何在iOS中的WebView(react-native-webview)中设置自定义字体?

imm*_*odi 5 ios react-native react-native-webview

我想在 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;
}
Run Code Online (Sandbox Code Playgroud)

它在 android 中运行良好,但在 iOS 中不起作用。如果有人有解决方案,请告诉我。

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

Ger*_*man 2

  1. 根据平台设置以下字体URL:
    const fontUrl = Platform.select({
        ios: "Poppins-Bold.ttf",
        android: "file:///android_asset/fonts/Poppins-Bold.ttf",
    });
    
    Run Code Online (Sandbox Code Playgroud)
  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;
         }`
    
    Run Code Online (Sandbox Code Playgroud)
    • 请注意,format('truetype')由于您的字体扩展名是ttf. 如果您使用某种eot字体,则需要使用format('opentype').
  3. 完成此操作后,请WebView使用以下属性更新您的组件:
    <WebView 
        source={{ html, baseUrl: '' }}
        originWhitelist={["*"]}
    />
    
    Run Code Online (Sandbox Code Playgroud)
    • 设置baseUrl为空白将确保加载字体。参考这篇文章。
    • 如果不设置originWhitelist,您将在 iOS 上收到无法找到 URL 的错误。

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