Search code examples
swiftswift-package-manager

Load fonts from a Swift Package


I wonder if there is a way to load fonts from a Swift Package at the moment? The font files are there in the package but the compiled program can't locate them.


Solution

  • ✅ It is supported now

    From Swift 5.3, you can add any resources to the target, including images, assets, fonts, zip, etc. Using the directory name will include all subfiles of the directory:

        .target(
            name: "ABUIKit",
            dependencies: [],
            resources: [.process("Resources") // <- this will add Resource directory to the target
            ]
        ),
    

    Note that you should put the Resources folder under sources/packageName to make it recognizable.

    ⚠️ Also, Don't forget to register them!

    You need to register fonts to make it work. So you can use frameworks like FontBlaster.

    NOTE: You can always write your own code, but I prefer to use an existing framework and contribute my extra needs to them

    So you call this somewhere early in the module's code (like some init method):

    FontBlaster.blast(bundle: .module)
    

    Then you can use the font inside or even outside of the module!


    🛑 There is no need to name the font manually!

    It will register all included fonts automatically. You can double-check the loaded fonts right after calling the blast method:

    FontBlaster.loadedFonts.forEach { print("🔠", $0) }