0

Before anyone marks it duplicate, I have already checked this post but no help.

I have created a framework, and in that framework I've created some UI. Now I want to use custom fonts for that UI, and those custom fonts name would be provided by the user itself. To make it more clear: I have a framework, I have imported in my existing project. Now I have to show a popup via framework.

MyFramework.showPopup()

But here, user will specify the fonts for that popup, i.e.

MyFramework.showPopup(regularFont: FontA.otf, boldFont: FontB.otf)

These fonts are already added in the project where I have imported the framework. I just need a way to load these fonts from inside framework. Any help would be appreciated. Thanks.

Abu Bäkr
  • 313
  • 1
  • 2
  • 10

1 Answers1

0

You need to register your local fonts (those that lives inside the Framework) in order to be recognized by the UIFonts API. Once you register your fonts, then they will be available to be used from outside the Framework. Make sure to call only once this method to avoid fonts duplication or possible crashes.

extension UIFont {
static func registerFonts(from bundle: Bundle) {
    print("Registering local fonts...")
    let fontUrls = bundle.urls(forResourcesWithExtension: "ttf", subdirectory: nil)!
    fontUrls.forEach { url in
        let fontDataProvider = CGDataProvider(url: url as CFURL)!
        let font = CGFont(fontDataProvider)!
        
        print(font.fullName)
        
        var error: Unmanaged<CFError>?
        guard CTFontManagerRegisterGraphicsFont(font, &error) else {
            fatalError("Could not register font from url \(url), error: \(error!.takeUnretainedValue())")
        }
    }
    print("Registering Ended")
}

}

Yisus
  • 159
  • 1
  • 4