Xcode: Using custom fonts inside Dynamic framework

前端 未结 9 1585
再見小時候
再見小時候 2020-12-04 17:52

I added custom font to a framework. I followed all the steps, but it doesn\'t work.

I am able to set the font in Interface Builder, but when I build the project it d

9条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 18:31

    Swift 4:

    This is maybe an old thread but has updated @xaphod for swift 4 as all static and global variables are lazily initialised using dispatch_once.

    extension UIFont {
    
    // load framework font in application
    public static let loadAllFonts: () = {
        registerFontWith(filenameString: "SanFranciscoText-Regular.otf", bundleIdentifierString: "Fonts")
        registerFontWith(filenameString: "SanFranciscoText-Medium.otf", bundleIdentifierString: "Fonts")
        registerFontWith(filenameString: "SanFranciscoText-Semibold.otf", bundleIdentifierString: "Fonts")
        registerFontWith(filenameString: "SanFranciscoText-Bold.otf", bundleIdentifierString: "Fonts")
        registerFontWith(filenameString: "SanFranciscoText-LightItalic.otf", bundleIdentifierString: "Fonts")
    }()
    
    //MARK: - Make custom font bundle register to framework
    static func registerFontWith(filenameString: String, bundleIdentifierString: String) {
        let frameworkBundle = Bundle(for: MSAlertController.self)
        let resourceBundleURL = frameworkBundle.url(forResource: bundleIdentifierString, withExtension: "bundle")
        if let url = resourceBundleURL, let bundle = Bundle(url: url) {
            let pathForResourceString = bundle.path(forResource: filenameString, ofType: nil)
            if let fontData = NSData(contentsOfFile: pathForResourceString!), let dataProvider = CGDataProvider.init(data: fontData) {
                let fontRef = CGFont.init(dataProvider)
                var errorRef: Unmanaged? = nil
                if (CTFontManagerRegisterGraphicsFont(fontRef!, &errorRef) == false) {
                    print("Failed to register font - register graphics font failed - this font may have already been registered in the main bundle.")
                }
            }
        }
        else {
            print("Failed to register font - bundle identifier invalid.")
        }
    }
    }
    

    Then you can call UIFont.loadAllfont inside the appDelegate

提交回复
热议问题