iOS: Programmatically add custom font during runtime

后端 未结 4 1553
醉酒成梦
醉酒成梦 2020-12-01 05:01

I would like to allow my application users to use their own fonts in the app, by copying them inside the Documents directory (through iTunes). However, I can\'t find a way t

4条回答
  •  北海茫月
    2020-12-01 05:17

    extension UIFont {
    
        func registerNewFontFromAppBundle(withSize: CGFloat) {
            guard let filePath = Bundle.main.url(forResource: "Art Brewery", withExtension: "ttf") else { return }
            guard let dataProvider = CGDataProvider(url: filePath as CFURL), let cgFont = CGFont(dataProvider) else { return }
    
            var error: Unmanaged?
            if !CTFontManagerRegisterGraphicsFont(cgFont, &error)
            {
                print("Error registering Font")
            } else {
                guard let uiFont = UIFont(name: cgFont.postScriptName! as String, size: withSize) else { return  }
                CurrentTheme.shared.currentFont = uiFont
            }
        }
    
        func registerNewFontFromDownloadedFiles(withSize: CGFloat) {
             guard let filePath = FileUtils().getFilePathAtDocumentFolder(fileName: "Art Brewery.ttf") else { return }
    
            if FileUtils.fileExists(atPath: filePath) {
              let url = URL(fileURLWithPath: filePath)
            guard let dataProvider = CGDataProvider(url: url as CFURL), let cgFont = CGFont(dataProvider) else { return }
    
            var error: Unmanaged?
            if !CTFontManagerRegisterGraphicsFont(cgFont, &error)
            {
                print("Error registering Font")
            } else {
                guard let uiFont = UIFont(name: cgFont.postScriptName! as String, size: withSize) else { return  }
                CurrentTheme.shared.currentFont = uiFont
                CurrentTheme.shared.currentFontName = cgFont.postScriptName! as String
            }
        }
    
        }
    }
    

    Usage :

    UIFont.registerNewFontFromAppBundle(withSize: 30)
    UIFont.registerNewFontFromDownloadedFiles(withSize: 30)
    mylabel.font =  CurrentTheme.shared.currentFont // saved the font in a Singleton
    or 
    mylabel.font = UIFont(name: CurrentTheme.shared.currentFontName, size: 30) // Saved the Font name to reuse
    

提交回复
热议问题