Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 885
Fabez Avatar asked Oct 25 '25 02:10

Fabez


1 Answers

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 {
        //
    }
}
like image 134
Fabez Avatar answered Oct 26 '25 16:10

Fabez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!