简体   繁体   中英

How to use custom fonts from a framework generated within Xcode workspace

I am trying to encapsulate and organise my Xcode project per features. To achieve this, I am creating a Framework project embedded in the main project. The framework contains all the app appearance (with color definition and custom fonts).

My project structure is something similar to this:

MainProject
    |_ Appearance.xcodeproj
    |       |_ ... 
    |       |_ Controller.swift
    |       |_ Resources
    |             |_ Font1.ttf
    |             |_ Font2.ttf
    |       |_ Products
    |             |_ Appearance.framework
    |_ ...

The idea is to compile Appearance.framework only once and use embedded custom fonts from the main project. Although, the headers are exposed and there is no compilation errors, I am getting runtime errors.

The controller in the framework uses UIFont(name: "Font1", size: 9)! But, the return is nil

I read about adding the fonts fullpath on main project Info.plist. Nevertheless, the framework is local and not managed by cocoapods. So the output is derived data.

Is this the proper way to embedded this kind of framework? Can anyone provide a solution for this purpose? I don't have any problem on changing my approach.

UPDATE 1:

Also, I noticed the framework is generated in XCode Derived Data folder. There is any chance, the framework can be generated on the local folder, so it can be tracked on GIT?

This is how you register the fonts in memory:

extension UIFont {
    private static func registerFont(withName name: String, fileExtension: String) {
        let frameworkBundle = Bundle(for: AnyClassFromFramework.self)
        let pathForResourceString = frameworkBundle.path(forResource: name, ofType: fileExtension)
        let fontData = NSData(contentsOfFile: pathForResourceString!)
        let dataProvider = CGDataProvider(data: fontData!)
        let fontRef = CGFont(dataProvider!)
        var errorRef: Unmanaged<CFError>? = nil

        if (CTFontManagerRegisterGraphicsFont(fontRef!, &errorRef) == false) {
            print("Error registering font")
        }
    }

    public static func loadFonts() {
        registerFont(withName: "Font1", fileExtension: "ttf")
        registerFont(withName: "Font2", fileExtension: "ttf")
    }
}

Call UIFont.loadFonts() in AppDelegate.swift.

You should be able afterward to create your UIFont(name: "Font1", size: 17) .

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