Created
January 20, 2023 13:29
-
-
Save mdb1/07048ee9eaf93b33c311ea6bfe5ecbd1 to your computer and use it in GitHub Desktop.
Register Custom Fonts
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
| import CoreGraphics | |
| import CoreText | |
| import UIKit | |
| enum FontError: Swift.Error { | |
| case failedToRegisterFont | |
| } | |
| func registerFont(named name: String) throws { | |
| guard let asset = NSDataAsset(name: "Fonts/\(name)", bundle: Bundle.module), | |
| let provider = CGDataProvider(data: asset.data as NSData), | |
| let font = CGFont(provider), | |
| CTFontManagerRegisterGraphicsFont(font, nil) else { | |
| throw FontError.failedToRegisterFont | |
| } | |
| } | |
| struct PublicSansFont { | |
| let name: String | |
| private init(named name: String) { | |
| self.name = name | |
| do { | |
| try registerFont(named: name) | |
| } catch { | |
| let reason = error.localizedDescription | |
| fatalError("Failed to register font: \(reason)") | |
| } | |
| } | |
| static let light = PublicSansFont(named: "PublicSans-Light") | |
| static let regular = PublicSansFont(named: "PublicSans-Regular") | |
| static let medium = PublicSansFont(named: "PublicSans-Medium") | |
| static let semiBold = PublicSansFont(named: "PublicSans-SemiBold") | |
| static let bold = PublicSansFont(named: "PublicSans-Bold") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment