Last active
September 21, 2024 03:34
-
-
Save muizidn/5c314f96b9f536308eb20b79894b220c to your computer and use it in GitHub Desktop.
Using custom font in iOS without register to Info.plist
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FontLoader { | |
private enum Error: Swift.Error { | |
case error(String) | |
} | |
/// Register fonts | |
/// | |
/// - Parameter fonts: Font names | |
static func registerFonts(fonts: [String]) throws { | |
let bundle = Bundle(for: FontLoader.self) | |
let urls = fonts.compactMap({ bundle.url(forResource: $0, withExtension: "ttf") }) | |
try urls.forEach { (url) in | |
let data = try Data.init(contentsOf: url) | |
guard let provider = CGDataProvider.init(data: data as CFData) else { throw Error.error("CGDataProvider nil") } | |
guard let font = CGFont.init(provider) else { throw Error.error("CGFont nil") } | |
var error: Unmanaged<CFError>? | |
guard CTFontManagerRegisterGraphicsFont(font, &error) else { | |
throw error!.takeUnretainedValue() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.