Skip to content

Instantly share code, notes, and snippets.

@alexj70
Last active April 25, 2017 17:23
Show Gist options
  • Save alexj70/dd3654bcb3a775babd2fb12acc9d37e7 to your computer and use it in GitHub Desktop.
Save alexj70/dd3654bcb3a775babd2fb12acc9d37e7 to your computer and use it in GitHub Desktop.
Font

UIFont

import UIKit.UIFont
protocol FontConvertible {
    func font(size: CGFloat) -> UIFont
}

extension FontConvertible where Self: RawRepresentable, Self.RawValue == String {
    func font(size: CGFloat) -> UIFont {
        return UIFont(font: self, size: size)
    }
}

struct FontFamily {
    enum AcierBATText: String, FontConvertible, Iteratable {
        case noir = "AcierBATText-Noir"
    }
    
    enum Roboto: String, FontConvertible, Iteratable {
        case regular = "Roboto-Regular"
        case medium = "Roboto-Medium"
        case bold = "Roboto-Bold"
        case black = "Roboto-Black"
    }
    
}

extension UIFont {
    convenience init<FontType: FontConvertible> (font: FontType, size: CGFloat) where FontType: RawRepresentable, FontType.RawValue == String {
        self.init(name: font.rawValue, size: size)!
    }
}

Enum iteration

Using

let helvetica = UIFont(font: FontFamily.Roboto.regular, size: 20.0)
let helveticaNeue = FontFamily.Roboto.regular.font(size: 20.0)

Get list of all fonts

extension UIFont {
    class func printFonts() {
        let fontFamilyNames = UIFont.familyNames
        for familyName in fontFamilyNames {
            print("------------------------------")
            print("Font Family Name = [\(familyName)]")
            let names = UIFont.fontNames(forFamilyName: familyName)
            print("Font Names = [\(names)]")
            if familyName.contains("HFF") {
                print("we are here")
            }
        }
    }
}

Unit tessting

import XCTest
@testable import LIQR
class FontTests: XCTestCase {
    func test_RobotoFonts() {
        checkFonts(FontFamily.Roboto.self)
    }
    
    func test_AcierBATText() {
        checkFonts(FontFamily.AcierBATText.self)
    }
    
    func checkFonts<T: RawRepresentable>(_: T.Type) where T: Iteratable, T: FontConvertible, T: Hashable, T.RawValue == String {
        for font in T.hashValues() {
            XCTAssertNotNil(font.font(size: 20), "\(font.rawValue)")
            XCTAssertNotNil(UIFont(font: font, size: 20.0), "\(font.rawValue)")
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment