Swift动态加载字体(不写plist)

想弄一个动态加载字体的功能,结果网上翻来翻去没有Swift版的,只能自己折腾,还好折腾两天折腾出来了(没办法,对Core Graphics不熟呀).刚学Swift,不知道这么写的对不对(可能会有对象释放的问题),望大佬看出来了指点指点~
OC版传送门: https://www.aliyun.com/jiaocheng/359216.html

    // ...读取本地字体文件
    let path = Bundle.main.path(forResource: "XXXXXX", ofType: "ttf")!
    let fontData = NSData.init(contentsOfFile: path)
    
    // ...通过CGDataProvider承载生成CGFont对象
    let fontDataProvider = CGDataProvider(data: CFBridgingRetain(fontData) as! CFData)
    let fontRef = CGFont.init(fontDataProvider!)!
    
    // ...注册字体
    var fontError = Unmanaged?.init(nilLiteral: ())
    CTFontManagerRegisterGraphicsFont(fontRef, &fontError)

    // ...获取了字体实际名字
    let fontName:String =  fontRef.fullName! as String
    
    
    self.wordLabel.font = UIFont.init(name: fontName, size: self.bounds.width*0.8)

你可能感兴趣的:(Swift动态加载字体(不写plist))