小编典典

Xcode:在动态框架内使用自定义字体

swift

我在框架中添加了自定义字体。我遵循了所有步骤,但是没有用。

我可以在Interface Builder中设置字体,但是在构建项目时,它不会在模拟器/设备上显示该字体。


阅读 248

收藏
2020-07-07

共1个答案

小编典典

我来晚了一点,但是我采用了PetahChristian的解决方案,并以扩展的形式创建了Swift版本。这对我有用。我发现,当您尝试使用常规名称来使用字体名称和大小来获取字体时,它总是在字体文件的主捆绑包中查找,并且没有将捆绑包标识符作为参数的方法。如果苹果能制造一款,那将是很好的。

迅速:

public extension UIFont {

    public static func jbs_registerFont(withFilenameString filenameString: String, bundle: Bundle) {

        guard let pathForResourceString = bundle.path(forResource: filenameString, ofType: nil) else {
            print("UIFont+:  Failed to register font - path for resource not found.")
            return
        }

        guard let fontData = NSData(contentsOfFile: pathForResourceString) else {
            print("UIFont+:  Failed to register font - font data could not be loaded.")
            return
        }

        guard let dataProvider = CGDataProvider(data: fontData) else {
            print("UIFont+:  Failed to register font - data provider could not be loaded.")
            return
        }

        guard let font = CGFont(dataProvider) else {
            print("UIFont+:  Failed to register font - font could not be loaded.")
            return
        }

        var errorRef: Unmanaged<CFError>? = nil
        if (CTFontManagerRegisterGraphicsFont(font, &errorRef) == false) {
            print("UIFont+:  Failed to register font - register graphics font failed - this font may have already been registered in the main bundle.")
        }
    }

}

用法示例:

UIFont.jbs_registerFont(
    withFilenameString: "Boogaloo-Regular.ttf",
    bundle: Bundle(identifier: "com.JBS.JBSFramework")!
)
2020-07-07