Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

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

I'm creating an ios framework with its bundle for packaging ressources (nib, images, fonts) and I'm trying to embed a custom font in the bundle but I'm not able to load it from the framework, is it possible ?

1) I can localize the font file with this: objc NSString *fontPath = [[NSBundle frameworkBundle] pathForResource:@"MyCustomFont" ofType:@"ttf"]; 2) But I can't get it in my fonts lists: objc NSArray * array = [UIFont familyNames]; I included my font name in the bundle's plist with a "Fonts provided by application", without success, tried also in the app info plist, include it in the framework ressource without success.

I can load the nib and images from the bundle (by prefixing with the bundle's name) but not for the font. Any thought ?

EDIT : I saw the following post : Can I embed a custom font in an iPhone application?, but the question is just "Can I embed a custom font in an iPhone application?" not "Can I embed a custom font in an external framework/bundle ?" It also makes references to a dynamic loading which is interesting but it is using private api, which is not usable solution for a framework.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...