ios动态注册加载字体文件方法,无需在Info.plist文件中配置

extension UIFont {
    /// 动态字体获取
    static func font(name: String, size: CGFloat, of type: String = "ttf") -> UIFont {
        let fontName = loadFontFile(name, ofType: type)
        return UIFont.init(name: fontName, size: size) ?? UIFont.systemFont(ofSize: size)
    }
    
    /// 加载本地字体
    static func loadFontFile(_ name: String, ofType type: String = "ttf", target bundle: Bundle = .main) -> String {
        var fullName: String = ""
        guard let path = bundle.path(forResource: name, ofType: type) else {
            return ""
        }
        if let fontData = NSData(contentsOfFile: path) {
            fullName = registerFont(fontData: fontData)
        }
        return fullName
    }
    
    /// 动态注册字体文件
    static func registerFont(fontData: NSData) -> String {
        // ...通过CGDataProvider承载生成CGFont对象
        let fontDataProvider = CGDataProvider(data: CFBridgingRetain(fontData) as! CFData)
        let fontRef = CGFont(fontDataProvider!)!
        // ...注册字体
        var fontError = Unmanaged?.init(nilLiteral: ())
        CTFontManagerRegisterGraphicsFont(fontRef, &fontError)
        // ...获取了字体实际名字
        let fullName: String = fontRef.fullName! as String
        let postScriptName: String = fontRef.postScriptName! as String
        return fullName
    }
}

你可能感兴趣的:(ios动态注册加载字体文件方法,无需在Info.plist文件中配置)