前言

react native项目中经常会用到icon,react-native-vector-icons字体库解决了一部分icon的需求,但是还有一部分设计师给的icon需要在iconfont自行引用,关于使用react-native-vector-icons遇到的坑在之前的文章提到过react native新建项目踩坑记录(字体问题详见问题五),主要是两点:

  1. 不要link react-native-vector-icons
    使用react-native unlink react-native-vector-icons
  2. ios路径下Info.plist文件添加字体映射,详见<key>UIAppFonts</key>的值

ios环境下引用iconfont

  1. 下载iconfont,解压后会得到其中一个iconfont.ttf的字体文件。
  2. 在rn项目src(react业务代码根目录)下新建assets/fonts目录,复制解压后的目录:
  3. 打开package.json文件,配置字体路径:
    1
    2
    3
    4
    5
    "rnpm": {
    "assets": [
    "./src/assets/fonts/"
    ]
    }
  4. 执行以下命令,执行完成后,重启编辑器(注意文章开头提醒的,如果有安装react-native-vector-icons字体库的,这里你link后运行项目肯定报错了,需要重复开头的两个步骤),link后
  5. 如果不执行第四步,你xcode打开你的ios项目,可能是没有Resource目录的
  6. 如果执行完第四步,重启后会发现该字体文件已经自动拷贝到 android/app/src/main/assets/fonts目录

    和配置到Info.plist文件中, 那么你可以直接看最后一步。
  7. 如果没有出现第六步所诉的预期,那么,此时你再打开xcode,应该有Resource这个目录了,如果之前本来就有的可以忽略这句话
  8. 复制ttf文件到Resource目录下,松开鼠标会弹出来弹窗,选择
  9. 去Info.plist中添加 Fonts provided by application,然后在其底下添加子项,value值为字体文件名称,如有多个,则添加多个子项,一个子项对应一个字体文件
  10. 添加完去rn项目下ios路径下的Info.plist文件查看字体完整配置:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <key>UIAppFonts</key>
    <array>
    <string>iconfont.ttf</string>
    <string>AntDesign.ttf</string>
    <string>Entypo.ttf</string>
    <string>EvilIcons.ttf</string>
    <string>Feather.ttf</string>
    <string>FontAwesome.ttf</string>
    <string>FontAwesome5_Brands.ttf</string>
    <string>FontAwesome5_Regular.ttf</string>
    <string>FontAwesome5_Solid.ttf</string>
    <string>Fontisto.ttf</string>
    <string>Foundation.ttf</string>
    <string>Ionicons.ttf</string>
    <string>MaterialCommunityIcons.ttf</string>
    <string>MaterialIcons.ttf</string>
    <string>Octicons.ttf</string>
    <string>SimpleLineIcons.ttf</string>
    <string>Zocial.ttf</string>
    </array>
  11. 使用unicode显示字体
  12. 效果

安卓环境下引用iconfont

待补充…