vds_ios/VDS/Fonts/FontProtocol.swift
Matt Bruce 02150f8e8c added helper for scaledFonts
Signed-off-by: Matt Bruce <matt.bruce@verizon.com>
2023-07-21 10:43:55 -05:00

55 lines
1.7 KiB
Swift

//
// FontStyle.swift
// VDS
//
// Created by Matt Bruce on 7/27/22.
//
import Foundation
import UIKit
public protocol FontProtocol: CaseIterable, RawRepresentable, Hashable {
var fontFileExtension: String { get }
var fontName: String { get }
}
extension FontProtocol {
public func register() {
guard let bundle = Bundle(identifier: "com.vzw.vds") else { return }
Self.allCases.forEach{ font in
if let url = bundle.url(forResource: font.fontName, withExtension: font.fontFileExtension){
do{
try Self.register(from: url)
} catch{
//TODO: error ("Font called \(font.fontName).\(font.fontFileExtension) couldn't be registered")
}
} else {
//TODO: error ("Font for FontStyle: \(font) couldn't be found")
}
}
}
public static func register(from url: URL) throws {
guard let fontDataProvider = CGDataProvider(url: url as CFURL) else {
throw NSError(domain: "www.verizon.com", code: 123, userInfo: ["description":"Could not create font data provider for \(url)."])
}
let font = CGFont(fontDataProvider)
var error: Unmanaged<CFError>?
guard CTFontManagerRegisterGraphicsFont(font!, &error) else {
throw error!.takeUnretainedValue()
}
}
public func font(ofSize size: CGFloat, isScaled: Bool = true) -> UIFont{
DispatchQueue.once(block: { self.register() })
guard let found = UIFont(name: self.fontName, size: size) else { return .systemFont(ofSize: size) }
return found
}
}
extension UIFont {
public var scaledFont: UIFont {
UIFontMetrics.default.scaledFont(for: self)
}
}