Skip to content

Instantly share code, notes, and snippets.

@mdb1
Created January 20, 2023 13:29
Show Gist options
  • Select an option

  • Save mdb1/07048ee9eaf93b33c311ea6bfe5ecbd1 to your computer and use it in GitHub Desktop.

Select an option

Save mdb1/07048ee9eaf93b33c311ea6bfe5ecbd1 to your computer and use it in GitHub Desktop.
Register Custom Fonts
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