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

后端 未结 7 1329
北荒
北荒 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 02:55

    Updated for Swift 4/5 and changed to throw errors instead of returning a Bool.

    enum FontLoadingError: Error {
        case fileNotFound
        case unreadableFontData
    }
    
    func loadCustomFont(name: String) throws {
        guard let fontURL = frameworkBundle.url(forResource: name, withExtension: "ttf") else {
            throw FontLoadingError.fileNotFound
        }
    
        guard
            let provider = CGDataProvider(url: fontURL as CFURL),
            let font = CGFont(provider)
        else {
            throw FontLoadingError.unreadableFontData
        }
    
        var cfError: Unmanaged?
        CTFontManagerRegisterGraphicsFont(font, &cfError)
    
        if let error = cfError as? Error {
            throw error
        }
    }
    

提交回复
热议问题