【问题标题】:Custom font in Swift 5 not working in Xcode 10Swift 5 中的自定义字体在 Xcode 10 中不起作用
【发布时间】:2019-05-22 08:22:14
【问题描述】:

我正在尝试在 Xcode 10 中添加自定义字体,但我不断收到此错误:

致命错误:在展开可选值时意外发现 nil

  • 我已将字体包含在我的 Info.plist 中
  • 我检查了我的“复制捆绑资源”,它就在那里。

我仍然收到此错误。

下面是我的代码:

DispatchQueue.main.async {
    let paragraph = NSMutableParagraphStyle()
    paragraph.alignment = .center

    let attributedString = NSAttributedString(string: message, attributes:
        [.paragraphStyle: paragraph, NSAttributedString.Key.font : UIFont (name: "Lato-Regular", size: 14)!]) // Throws error here

    let alert = UIAlertController(title: title, message: "", preferredStyle: .alert)
    alert.setValue(attributedString, forKey: "attributedMessage")

    alert.addAction(UIAlertAction(title: "Back", style: .cancel, handler: nil))
    self.present(alert, animated: true)
}

在这一行引发错误

UIFont (name: "Lato-Regular", size: 14)!

Xcode 找不到字体,但我也可以在 Storyboard UI 上使用该字体。那怎么来的?

【问题讨论】:

  • Story board UI 中的字体名称是什么?检查拼写
  • 试试这个:UIFont(name: "Lato", size: 14)!
  • @BhavinRamani 谢谢,但遇到同样的错误
  • @karthikeyan 我的字体有正确的名称,我在另一个旧项目中使用过它并且效果很好。

标签: ios swift uifont


【解决方案1】:

UIFont.familyNames 将为您提供所有可用字体系列的列表。 UIFont.fontNames(forFamilyName:) 将为您提供所有字体名称。使用它来找出正确的字体名称。

let families = UIFont.familyNames
let allFonts = families.flatMap { UIFont.fontNames(forFamilyName:$0) }
let latoFonts = allFonts.filter { $0.contains("Lato") }
print(latoFonts)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 2018-08-28
    • 1970-01-01
    • 2013-09-27
    • 2012-05-09
    • 1970-01-01
    • 2012-09-11
    相关资源
    最近更新 更多