Skip to main content
 首页 » 操作系统

swift之如何将下载的自定义字体添加到 Swift 中的导航栏标题

2024年01月01日45zhengyun_ustc

我下载了一个很酷的字体,想用它作为我的应用程序的导航栏标题,但似乎无法让应用程序识别/显示它。每次运行尝试都会抛出异常。这是我采取的步骤。

  1. 我将 myCustomFont.ttf 文件移动到项目中,就像我移动其他支持文件(图像等)一样
  2. 更新了我的 info.plist 文件,添加了 应用程序提供的字体,并将文件名添加到数组中
  3. 然后,我将以下代码添加到 AppDelegate.swift


// Navigation bar customization 
let navigationController = window!.rootViewController as UINavigationController 
 
navigationController.navigationBar.titleTextAttributes = [NSFontAttributeName : (UIFont(name: "myCustomFont", size: 10))!] 

如果我将 myfont 替换为 Times New Roman 或 Arial 之类的标准内容,则上述代码可以正常工作。

任何帮助将不胜感激。谢谢!

请您参考如下方法:

确保您的字体在 Bundle Resources 中。出于某种原因,Xcode 大多数时候都没有正确导入自定义字体:

然后在 AppDelegate 中试试这个

UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : UIFont(name: "JennaSue", size: 20)!, NSForegroundColorAttributeName : uicolorFromHex(0x5C8CA7)]