Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Extension to UIFont that allows to create a monospaced digits font from a instance of UIFont. If the font is not a San Francisco font it simply returns self.
// UIFont+MonospacedDigitsFont.swift
// Created by Samuel Mellert on 29/12/15.
import UIKit
extension UIFont {
func monospacedDigitsFont() -> UIFont {
if #available(iOS 9, *) {
guard self.fontName.hasPrefix(".SFUI") else {
return self
guard self.fontName.componentsSeparatedByString("-").count == 2,
let weightSuffix = self.fontName.componentsSeparatedByString("-").last else {
return UIFont.monospacedDigitSystemFontOfSize(self.pointSize, weight: UIFontWeightRegular)
let fontWeight: CGFloat
switch weightSuffix {
case "Ultralight":
fontWeight = UIFontWeightUltraLight
case "Light":
fontWeight = UIFontWeightLight
case "Thin":
fontWeight = UIFontWeightThin
case "Regular":
fontWeight = UIFontWeightRegular
case "Medium":
fontWeight = UIFontWeightMedium
case "Semibold":
fontWeight = UIFontWeightSemibold
case "Bold":
fontWeight = UIFontWeightBold
case "Heavy":
fontWeight = UIFontWeightHeavy
case "Black":
fontWeight = UIFontWeightBlack
fontWeight = UIFontWeightRegular
return UIFont.monospacedDigitSystemFontOfSize(self.pointSize, weight: fontWeight)
return self
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment