2

I'm using xCode 9.3.1 & Swift 4.1.

I'm trying to use SF Pro Text Medium font in my app code programatically. But this font is not found in the source code in swift file and app crashes.

Here is the code: NSAttributedStringKey.font: UIFont(name: ".SFProText-Medium", size: 24.0)!

At run time it throws following error: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Any other standard font work.

This font is available in the storyboard and I've used it successfully.

Why doesn't it work programatically? Do I've to add it in the xCode (plist etc) to make it work?

4

2 回答 2

3

请按照以下步骤操作,看看它是否适合您:


1) 将字体文件添加到您的项目中

2)在您info.plist按下它旁边的最顶部的加号按钮时Information Property List。类型Fonts provided by application(它应该为您自动完成)。像这样添加你的字体文件:

这个

3)在左侧菜单上按下您的项目,然后转到Build Phases并将您的字体文件添加到它说的位置Copy Bundle Sources


如果您不确定您的字体叫什么,请打印所有字体,直到找到您的字体名称。运行这个viewDidLoad

UIFont.familyNames.forEach({ familyName in
    let fontNames = UIFont.fontNames(forFamilyName: familyName)
    print(familyName, fontNames)
})
于 2018-05-15T00:58:35.983 回答
1

我是否必须将其添加到 xCode(plist 等)中才能使其正常工作?

确实。按照纳德的指示,确保字体文件将您的项目作为目标成员,如下所示:

在此处输入图像描述

于 2018-05-15T03:17:04.937 回答