Skip to content

Instantly share code, notes, and snippets.

@mpospese
Last active August 12, 2022 11:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpospese/953623406c0a2fa76b650a475202abfd to your computer and use it in GitHub Desktop.
Save mpospese/953623406c0a2fa76b650a475202abfd to your computer and use it in GitHub Desktop.

Introducing YMatterType

YMatterType is a framework that assists in getting typography done right when constructing iOS user interfaces from Figma-based designs.

YMatterType aims to achieve the following goals:

  • Support line height and other typographical properties (letter spacing, text decorations, text cases, and more) across labels, buttons, text fields, and text views.
  • Support Dynamic Type scaling and Accessibility Bold Text on custom fonts
  • Accelerate accurate translation of Figma designs into code by having text-based elements with the exact same intrinsic size (based upon line height) as the corresponding elements in Figma.

Typography

Typography represents type faces as they are typically presented in design files (whether that’s a full-blown design system or just a style guide). The aim is to define typography in our code exactly the same as it is defined by the designers, so that a label or a button in our application has the exact same dimensions and appearance (at default scaling) as the corresponding component in the design files. The crucial part of this (which is often overlooked when implementing user interfaces) is line height. It’s easy to use a 16 pt semibold San Francisco font, but to have it also have exactly a 24 pt line height requires extra engineering. YMatterType handles this for you.

More than just a font

Font is the principal part of typography, but not the only one. There are many other properties that determine how text is rendered: line height, letter spacing, text decorations, text case, etc. To that end we adopt an approach of setting typography on labels, buttons, text fields, and text views instead of setting a font. The typography generates the correct font to use based on the current trait environment and considers both Dynamic Type and the Accessibility Bold Text setting. (For example, that 16/24 pt semibold San Francisco font might actually be a 16/24 pt bold font if the user has Bold Text enabled. Or it might be scaled up to a 32/48 pt font depending on the Dynamic Type setting.) The font and other typographical properties are then used to render the text via attributed strings.

Defining a Typography

Typography is simply a struct with properties for the font family, font weight, font size, line height, etc. It has many properties with sensible defaults, but at a minimum you need to specify the font family, font weight, font size, and line height.

// Avenir Next, Bold 16/24 pts
let typography = Typography(
    familyName: "AvenirNext",
    fontWeight: .bold,
    fontSize: 16,
    lineHeight: 24
)

Your exact typography definitions of course will depend upon your design system, but we recommend using semantic naming and declaring static properties on an extension to the Typography struct.

extension Typography {
    /// Noto Sans, Semibold 32/36 pts
    static let largeTitle = Typography(
        familyName: "NotoSans",
        fontWeight: .semibold,
        fontSize: 32,
        lineHeight: 36,
        textStyle: .largeTitle // closest matching `UIFont.TextStyle` used for scaling
    )
    
    /// Noto Sans, Semibold 17/22 pts
    static let headline = Typography(
        familyName: "NotoSans",
        fontWeight: .semibold,
        fontSize: 17,
        lineHeight: 22,
        textStyle: .headline
    )
}

Using Typography

There are four classes (TypographyLabel, TypographyButton, TypographyTextField, and TypographyTextView) which subclass their corresponding UIKit classes (UILabel, UIButton, UITextField, and UITextView, respectively). They each have a required initializer that takes a Typography. This enables these controls to size themselves correctly to match the designs they are sourced from.

// using `Typography.largeTitle` as defined in the previous snippet
let label = TypographyLabel(typography: .largeTitle)
let button = TypographyButton(typography: .largeTitle)

You may also set the typography on any instance of these classes, similar to how you could set the font.

label.typography = .headline

What you should not do, however, is set the font property directly. Just set the typography and the class will take care of the font.

Registering Custom Fonts

Any custom fonts need to be included as assets in your application and registered with the system. If you're building a simple app then you can just add them to your project and list them in your app's Info.plist file as you normally would. If, however, you want to build them into a separate Swift package, then that's fine too, and Y—MatterType has an extension on UIFont that makes it easier to register (and unregister) your font files. It throws an error if the font cannot be registered (and also if it has already been registered), so you'll know when you have a problem. Note that you will need to specify subpath if you use .copy for the resources in your Swift package file (and probably won't need to specify it if you use .process).

// Register font file "SF-Pro-Text-Regular.otf"
try UIFont.register(
    name: "SF-Pro-Text-Regular",
    fileExtension: "otf",
    subpath: "Assets/Fonts",
    bundle: .module
)

Because Bundle.module is only available from within your Swift package, we recommend that you expose a helper method from within your Swift package to register the fonts and that internally references Bundle.module.

public struct NotoSansFontFamily {
    /// Register all 3 NotoSans fonts
    public static func registerFonts() throws {
        let names = makeFontNames()
        try names.forEach {
            try UIFont.register(name: $0, fileExtension: "ttf", bundle: .module)
        }
    }

    /// Unregister all 3 NotoSans fonts
    public static func unregisterFonts() throws {
        let names = makeFontNames()
        try names.forEach {
            try UIFont.unregister(name: $0, fileExtension: "ttf", bundle: .module)
        }
    }

    private static func makeFontNames() -> [String] {
        [
            "NotoSans-Regular",
            "NotoSans-Medium",
            // Semibold is used for medium fonts when Accessibility Bold Text is enabled
            "NotoSans-SemiBold"
        ]
    }
}

Which font weights to include

Fonts can come in up to 9 different weights, ranging from ultralight (100) to black (900), but not all font families will support every weight. Also you might not wish to include fonts for weights which your design system does not use in order to keep your bundle size as small as possible. However, in order to support the Accessibility Bold Text feature (which allows users to request a heavier weight font), for each font weight in your design system, you need to include the next heavier font weight as well. For example, if your design system only uses regular (400) and bold (700) weight fonts, you would need to include (and register) font files for regular (400), medium (500), bold (700), and heavy (800) weight fonts.

Using System Fonts

Just want to use the default system fonts? YMatterType has you covered.

extension Typography {
    /// System font, Semibold 17/22 pts
    static let headline = Typography(
        fontFamily: FontInfo.system,
        fontWeight: .semibold,
        fontSize: 17,
        lineHeight: 22,
        textStyle: .headline
    )
}

Or do you wish to use SF Pro Display and Text fonts (in regular or italic)? (You would need to bundle and register the font files you will use.) YMatterType has a font family for this as well.

extension Typography {
    /// SF Pro Text, Semibold 17/22 pts
    static let headline = Typography(
        fontFamily: .sfProText,
        fontWeight: .semibold,
        fontSize: 17,
        lineHeight: 22,
        textStyle: .headline
    )
}

Custom Font Families

YMatterType does its best to automatically map font family name, font style (regular or italic), and font weight (ultralight to black) into the registered name of the font so that it may be loaded using UIFont(name:, size:). (This registered font name may differ from the name of the font file and from the display name for the font family.) However, some font families may require custom behavior in order to properly load the font (e.g. the semibold font weight might be named "DemiBold" instead of the more common "SemiBold"). To support this you can declare a class or struct that conforms to the FontRepresentable protocol and use that to initialize your Typography instance. This protocol has four methods, each of which may be optionally overridden to customize how fonts of a given weight are loaded. The framework contains three different implementations of FontRepresentable for you to consider (FontInfo, SystemFontInfo, and SFProFontFamily).

In the event that the requested font cannot be loaded (either the name is incorrect or it was not registered), YMatterType will fall back to loading a system font of the specified point size and weight.

struct AppleSDGothicNeoInfo: FontRepresentable {
    /// Font family root name
    let familyName: String = "AppleSDGothicNeo"
    
    /// Generates a weight name suffix as part of a full font name. Not all fonts support all 9 weights.
    /// - Parameter weight: desired font weight
    /// - Returns: The weight name to use
    func weightName(for weight: Typography.FontWeight) -> String {
        switch weight {
        case .ultralight:
            return "UltraLight" // most font familes use ExtraLight
        case .thin:
            return "Thin"
        case .light:
            return "Light"
        case .regular:
            return "Regular"
        case .medium:
            return "Medium"
        case .semibold:
            return "SemiBold"
        case .bold, .heavy, .black:
            // this font family doesn't support weights higher than Bold
            return "Bold"
        }
    }
}

Overriding/Extending Typography UI elements

All four of YMatterType's UI elements can be subclassed and include common override points:

  • adjustFonts: called when preferred content size category or legibility weight changes
  • adjustColors: called when any trait that might affect color changes
  • adjustBreakpoint: called when horizontal or vertical size class changes

(These three methods are also each called when the view is initialized.)

adjustColors can be useful when you need to update cgColor values when the user switches between light and dark mode or when increased contrast mode has been enabled or disabled.

class BorderButton: TypographyButton {
    ...
    
    override func adjustColors() {
        super.adjustColors()
        layer.borderColor = UIColor.primaryBorder.cgColor
    }
}

Utilizing Breakpoints

Would you like to use different (larger) typographies for controls in full-screen tablet mode vs split-screen tablet or phone? The overridable adjustBreakpoints method is called when either the horizontal or vertical size class changes. This can be a good time to update your typography.

extension Typography {
    struct Label {
        /// Label / Large (18/24 pt, medium)
        static let large = Typography(
            familyName: "NotoSans",
            fontWeight: .medium,
            fontSize: 18,
            lineHeight: 24,
            textStyle: .body
        )

        /// Label / Medium (16/20 pt, medium)
        static let medium = Typography(
            familyName: "NotoSans",
            fontWeight: .medium,
            fontSize: 16,
            lineHeight: 20,
            textStyle: .callout
        )
    }
}

extension Typography.Label {
    /// Determines the typography to use based upon the current trait environment.
    /// - Parameter traitCollection: the trait collection to consider
    /// - Returns: `Label.large` when the horizontal size class is `.regular`,
    ///  otherwise returns `Label.medium`
    static func current(traitCollection: UITraitCollection) -> Typography {
        switch traitCollection.horizontalSizeClass {
        case .regular:
            return large
        case .unspecified, .compact:
            fallthrough
        @unknown default:
            return medium
        }
    }
}

class BreakpointButton: TypographyButton {
    // adjust breakpoint if necessary
    override func adjustBreakpoint() {
        super.adjustBreakpoint()
        typography = .Label.current(traitCollection: traitCollection)
        // You might also wish to update the padding around the button's title.
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment