Can I embed a custom font in a bundle and access it from an ios framework?

后端 未结 7 1318
北荒
北荒 2020-12-13 02:35

I\'m creating an ios framework with its bundle for packaging ressources (nib, images, fonts) and I\'m trying to embed a custom font

7条回答
  •  感动是毒
    2020-12-13 03:05

    In swift, I use the code below :

    public class func loadMyCustomFont(name:String) -> Bool{
      let fontPath = self.frameworkBundle().pathForResource(name, ofType: "ttf")!
      let inData = NSData(contentsOfFile:fontPath)
      var error: Unmanaged?
      let provider = CGDataProviderCreateWithCFData(inData)
      if let font = CGFontCreateWithDataProvider(provider) {
         CTFontManagerRegisterGraphicsFont(font, &error)
         if error != nil {
           print(error) //Or logged it
           return false
         }
    
    
          }
           return true
       }
    

    The frameworkBundle method :

    class func frameworkBundle() -> NSBundle{
           var bundle = NSBundle()
           var predicate = dispatch_once_t()
           dispatch_once(&predicate) {
              let mainBundlePath = NSBundle.mainBundle().bundlePath
              let frameworkBundlePath = mainBundlePath.stringByAppendingString("/myFramework.framework/")
              bundle = NSBundle(path: frameworkBundlePath)!
           }
           return bundle
     }
    

    Exemple of call : (In my case, i added all fonts in the Fonts folder)

    YouClassName.loadMyCustomFont("Fonts/Roboto-Regular")
    

    Your corrections and remarks are welcome !

提交回复
热议问题