Search code examples
swiftmacosfontsinfo.plistnsfont

Adding a custom font to macOS app using Swift


I followed a bunch of tutorials but it doesn’t work: I simply want to add a custom font to a macOS app.

What I tried essentially:

  1. Added the .ttf font-files to my project: Target Membership is set and I also made sure that the files are copied using Copy Files within Bundle Phases. After compiling I can see that all files are within the Bundle. So that seems to work perfectly fine.

enter image description here

  1. Info.plist: I added Fonts provided by application and created an item for every font-file I want to add (values like myFont.tff).

  2. I made sure that I use the correct font name. I installed the fonts on my system and configured a Label with Interface Builder so that it uses the desired font. I printed it’s value print(myLabel.font.fontName).

  3. Confusing: If the exactly same font-file I want to add to the app is installed in the systems Fontbook and activated, everything works well. When I deactivate it, it doesn’t work. For me that indicates that I am using the correct font name.

  4. I found ATSApplicationFontsPath and tried to add it to the Info.plist, but neither using a path (recommended by the docs) or values like . (which seemed to work for some people out there) worked out.

enter image description here

Appreciate any help!


Solution

  • I solved my problem by accident.

    I noticed that within the Bundle files, my fonts were included twice: They were copied to the "Resources" directory as well as to the subpath I declared in the "Copy Files" Build Phases. I removed the fonts from my project, added them again (without checking the "Target Membership") and added them in the Build Phases so they were copied just to the subpath. After that it worked.

    Additional notes:

    Turned out that Fonts provided by application is a iOS only property so it is not needed for an macOS implementation.

    Also, ATSApplicationFontsPath does not need any slashes. For example: Fonts should work just fine.

    I had a difficult time finding the correct names for .ttf font files and sometimes discovered some strange behaviour: NSFont picked randomly fonts (regular, medium, bold...) from a font family without any code changes. By using .otf files instead I could solve that too.