Xcode: Using custom fonts inside Dynamic framework

前端 未结 9 1550
再見小時候
再見小時候 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:26

    Here's my version of John's answer, showing how to call the function if you have lots of fonts

    import Foundation
    
    extension UIFont {
    
        @nonobjc static var loadAllFontsDO: dispatch_once_t = 0
    
        class func initialsAvatarFont() -> UIFont {
            loadAllFonts()
            if let retval = UIFont(name: "MyFontName", size: kInitialsAvatarFontSize) {
                return retval;
            } else {
                return UIFont.systemFontOfSize(kInitialsAvatarFontSize)
            }
        }
    
        class func loadAllFonts() {
            dispatch_once(&loadAllFontsDO) { () -> Void in
                registerFontWithFilenameString("thefontfilename.ttf", bundleIdentifierString: "nameOfResourceBundleAlongsideTheFrameworkBundle")
                // Add more font files here as required
            }
        }
    
        static func registerFontWithFilenameString(filenameString: String, bundleIdentifierString: String) {
            let frameworkBundle = NSBundle(forClass: AnyClassInYourFramework.self)
            let resourceBundleURL = frameworkBundle.URLForResource(bundleIdentifierString, withExtension: "bundle")
            if let bundle = NSBundle(URL: resourceBundleURL!) {
                let pathForResourceString = bundle.pathForResource(filenameString, ofType: nil)
                let fontData = NSData(contentsOfFile: pathForResourceString!)
                let dataProvider = CGDataProviderCreateWithCFData(fontData)
                let fontRef = CGFontCreateWithDataProvider(dataProvider)
                var errorRef: Unmanaged? = nil
    
                if (CTFontManagerRegisterGraphicsFont(fontRef!, &errorRef) == false) {
                    NSLog("Failed to register font - register graphics font failed - this font may have already been registered in the main bundle.")
                }
            }
            else {
                NSLog("Failed to register font - bundle identifier invalid.")
            }
        }
    }
    

提交回复
热议问题