Xcode: Using custom fonts inside Dynamic framework

前端 未结 9 1577
再見小時候
再見小時候 2020-12-04 17:52

I added custom font to a framework. I followed all the steps, but it doesn\'t work.

I am able to set the font in Interface Builder, but when I build the project it d

9条回答
  •  佛祖请我去吃肉
    2020-12-04 18:43

    I'm here a bit late, but I took PetahChristian's solution and created a Swift version in the form of an extension. This is working for me. I've found that when you try to get a font using a font name and a size using the regular way that it always looks in the main bundle for the font file, and there's no method that takes a bundle identifier as a parameter. It would be nice if Apple would make one.

    Swift:

    public extension UIFont {
    
        public static func jbs_registerFont(withFilenameString filenameString: String, bundle: Bundle) {
    
            guard let pathForResourceString = bundle.path(forResource: filenameString, ofType: nil) else {
                print("UIFont+:  Failed to register font - path for resource not found.")
                return
            }
    
            guard let fontData = NSData(contentsOfFile: pathForResourceString) else {
                print("UIFont+:  Failed to register font - font data could not be loaded.")
                return
            }
    
            guard let dataProvider = CGDataProvider(data: fontData) else {
                print("UIFont+:  Failed to register font - data provider could not be loaded.")
                return
            }
    
            guard let font = CGFont(dataProvider) else {
                print("UIFont+:  Failed to register font - font could not be loaded.")
                return
            }
    
            var errorRef: Unmanaged? = nil
            if (CTFontManagerRegisterGraphicsFont(font, &errorRef) == false) {
                print("UIFont+:  Failed to register font - register graphics font failed - this font may have already been registered in the main bundle.")
            }
        }
    
    }
    

    Usage Example:

    UIFont.jbs_registerFont(
        withFilenameString: "Boogaloo-Regular.ttf",
        bundle: Bundle(identifier: "com.JBS.JBSFramework")!
    )
    

提交回复
热议问题