简体   繁体   中英

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?

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 {
        //
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM