简体   繁体   English

如何从 iOS 框架加载/读取字体,这些字体已经添加到 Swift 的主项目中?

[英]How to load/Read Fonts from iOS framework, which are already added in main project in Swift?

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.我创建了一个框架,并在该框架中创建了一些 UI。 Now I want to use custom fonts for that UI, and those custom fonts name would be provided by the user itself.现在我想为该 UI 使用自定义字体,这些自定义字体名称将由用户自己提供。 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, ie但是在这里,用户将指定该弹出窗口的字体,即

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.谢谢。

You need to register your local fonts (those that lives inside the Framework) in order to be recognized by the UIFonts API.您需要注册本地字体(位于框架内的字体)才能被 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")
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM