This is the 9th day of my participation in Gwen Challenge

Iconfont appears more and more frequently in mobile development. For small projects, developers can create a project on IconFont, pick their own ICONS, and go through the entire design and coding process.

Iconfont is a powerful and rich library of vector ICONS created by the Alibaba team.

See the official help documentation on how to use Iconfont in the main project.

However, we may want to use iconfont or other custom fonts when doing modular development or creating a separate framework. This is not the same process used in the main project.

The solution is to register our fonts first, and then use the fonts in the framework in the bundle of the main project.

Two points to note before we begin:

  1. It needs to be configured in the framework without modifying anything in the main project;
  2. There is no need to modify the frameworkinfo.plist. (One needs to be addedUIAppFontkeyKey and value are array of font names.

The following is the specific approach:

import Foundation
enum RegisterFontError: Error {
  case invalidFontFile
  case fontPathNotFound
  case initFontError
  case registerFailed
}
class GetBundle {}
extension UIFont {
static func register(path: String.fileNameString: String.type: String) throws {
  let frameworkBundle = Bundle(for: GetBundle.self)
  guard let resourceBundleURL = frameworkBundle.path(forResource: path + "/" + fileNameString, ofType: type) else {
     throw FontError.fontPathNotFound
  }
  guard let fontData = NSData(contentsOfFile: resourceBundleURL),    let dataProvider = CGDataProvider.init(data: fontData) else {
    throw FontError.invalidFontFile
  }
  guard let fontRef = CGFont.init(dataProvider) else {
     throw FontError.initFontError
  }
  var errorRef: Unmanaged<CFError>? = nil
 guard CTFontManagerRegisterGraphicsFont(fontRef, &errorRef) else   { 
       throw FontError.registerFailed
  }
 }
}
Copy the code

Once you have added the font file to the framework, you can register the font by calling uifont.register (_:_:).

Note: Registered fonts can only be called once. It is also simple to implement, for example:

//Either lazy or static is ok
static var registerFonts: () -> Void = {
  UIFont.register(path:xxx, fileName: xxx, type: .ttf)

}()
Copy the code

Then call YourFont. ResisterFonts.

You can check whether the registration is successful by using the following methods:

UIFont.familyNames.forEach { (font) in
    print("Family Name: \($0)")
    UIFont.fontNames(forFamilyName: $0).forEach({
        print("--Font Name: \($0)")
    })
}
Copy the code

reference

Add Font In Customize Framework Swift 4.2