首页 > 解决方案 > 如何在 iOS 上使用带有 React Native 的 WebView 中的捆绑字体?

问题描述

在我的 React Native 应用程序中,我有一些信息存储在本地捆绑文件夹中,并显示在 WebView 中。我希望它与应用程序的其余部分保持一致,因此我需要使用与应用程序其余部分相同的字体。

我在 Android 中可以正常工作,但在 iOS 中我根本无法让它显示字体。

我的 Webview 屏幕如下所示:

export class InstructionView extends React.Component<InstructionScreenRouteProp> {

render(): JSX.Element {
 
  let filePath = (Platform.OS === 'android') ? 'file:///android_asset/' : './html/';
  filePath +=  this.props.route.params.file.file + '.html';

  return (
    <WebView
        originWhitelist={['*']}
        source={{ baseUrl:'',
          uri: filePath }}
    startInLoadingState = { true }
    />
  );
}
}

我的捆绑包的结构如下:

/html/instructions.html
/html/styles.css 
/Resources/MyFont-Regular.ttf

然后 css 文件字体声明如下所示:

@font-face {
  font-family: 'myFont';
  src: local('MyFont-Regular'), url('MyFont-Regular.ttf'), format('truetype');
}

h1 {
  font-family: 'myFont';
  font-size: 2em;
  background-color: #622a53;
  color: #fffcdc;
  padding: 0.5em;
}

我认为该字体目前无法在 Android 上运行,因为我一直在尝试找出它的 iOS 版本,但我之前使用显式路径让它在 Android 上运行,就像渲染中的文件路径一样功能。

html 已正确加载和呈现,样式表中的其他样式已应用,只是缺少字体。

我在不同的地方看到过各种关于这个的建议,但没有一个能让我满意,因为它们似乎依赖于将字体与 html 内容放在同一个文件夹中,甚至在样式表中进行编码,当我已经有了它时,这似乎是多余的包含在其他地方的应用程序包中。我在 font-face url 中尝试了很多不同的路径,但它们似乎都不起作用,但是由于 React 静默缓存资产的方式,很难知道我是否真的看到了我尝试过的所有东西。

我需要做什么才能在 iOS 设备上的 WebView 中使用现有字体?

标签: iosreact-nativewebwebview

解决方案


推荐阅读