Swift 5中的自定义字体在Xcode 10中不起作用

时间:2019-05-22 08:22:15

标签: ios swift uifont

我正在尝试在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上使用该字体。那怎么会呢?

1 个答案:

答案 0 :(得分:0)

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)