Can I embed a custom font in a bundle and access it from an ios framework?

后端 未结 7 1291
北荒
北荒 2020-12-13 02:35

I\'m creating an ios framework with its bundle for packaging ressources (nib, images, fonts) and I\'m trying to embed a custom font

相关标签:
7条回答
  • 2020-12-13 03:15

    Swift 3:

    Firstly, don't access framework bundle from main with appending path components... Instantiate it from its identifier. You can get font URLs like this:

    static func fontsURLs() -> [URL] {
        let bundle = Bundle(identifier: "com.company.project.framework")!
        let fileNames = ["Roboto-Bold", "Roboto-Italic", "Roboto-Regular"]
        return fileNames.map({ bundle.url(forResource: $0, withExtension: "ttf")! })
    }
    

    And I find it nice to have UIFont extension for registering fonts:

    public extension UIFont {
        public static func register(from url: URL) throws {
            guard let fontDataProvider = CGDataProvider(url: url as CFURL) else {
                throw SVError.internal("Could not create font data provider for \(url).")
            }
            let font = CGFont(fontDataProvider)
            var error: Unmanaged<CFError>?
            guard CTFontManagerRegisterGraphicsFont(font, &error) else {
                throw error!.takeUnretainedValue()
            }
        }
    }
    

    Now enjoy the registration:

    do {
        try fontsURLs().forEach({ try UIFont.register(from: $0) })
    } catch {
        print(error)
    }
    
    0 讨论(0)
提交回复
热议问题