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?

Matt
  • 315
  • 2
  • 6
  • 20

2 Answers2

3

Follow these steps and see if it works out for you:


1) Add font files to your project

2) In your info.plist press on the plus button at the very top next to where it says Information Property List. Type Fonts provided by application (it should autcomplete for you). Add your font files like this:

this

3) Press on your project on the left menu and go to Build Phases and add your font files to where it says Copy Bundle Sources


If you aren't sure what your font is called, print all the fonts until you find your font's name. Run this in viewDidLoad

UIFont.familyNames.forEach({ familyName in
    let fontNames = UIFont.fontNames(forFamilyName: familyName)
    print(familyName, fontNames)
})
Nader
  • 1,120
  • 1
  • 9
  • 22
  • Tx Nader, very detailed and step by step instructions. It worked like charm. The only mystery still bothering me is why we have to include system fonts if we have to use them programmatically when it is already available xCode and can be used in IB. I thought if it's already included in xCode IB it should be also available to be used programatically. – Matt May 15 '18 at 14:28
  • @Matt Tbh I am not sure, the font is supposed to be added to your `plist` and bundle sources in order to work so I would guess that this specific font is already on your mac so it appeared in your IB. Does the font actually appear when you run the app with the IB font? – Nader May 15 '18 at 16:28
1

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

Definitely. Follow Nader's instruction and make sure the font file is has your project as a targeted membership, like so:

enter image description here

Glenn Posadas
  • 12,555
  • 6
  • 54
  • 95