Search code examples
iosswiftxcodeswift-playgroundswiftpm

How to change font in Xcode Swift Playgrounds(.swiftpm) project?


How can I implement a custom font in the new Xcode Swift Playgrounds project? In the simple Xcode App project we do it importing the font and adding it in the info plist (fonts provided by application), but in this type of project there isn't the info plist, what should I do?


Solution

  • I found the solution by myself with the help of a friend, I had to create a public struct MyFont with a fileprivate static func, and then add an init inside the main file, before var body.

    This is the code:

    MyFont

    import SwiftUI
    
    public struct MyFont {
        public static func registerFonts() {
            registerFont(bundle: Bundle.main , fontName: "YOUR-FONT-HERE", fontExtension: ".ttf") //change according to your ext.
        }
        fileprivate static func registerFont(bundle: Bundle, fontName: String, fontExtension: String) {
            
            guard let fontURL = bundle.url(forResource: fontName, withExtension: fontExtension),
                  let fontDataProvider = CGDataProvider(url: fontURL as CFURL),
                  let font = CGFont(fontDataProvider) else {
                fatalError("Couldn't create font from data")
            }
            
            var error: Unmanaged<CFError>?
            
            CTFontManagerRegisterGraphicsFont(font, &error)
        }
    }
    

    MyApp

    @main
    struct MyApp: App {
    
        //add the init before var body
        init() {
            MyFont.registerFonts()
        }
        
        var body: some Scene {
            //
        }
    }