Skip to content

Instantly share code, notes, and snippets.

@samuel-mellert
Last active September 20, 2016 09:18
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 samuel-mellert/e693240229abd44b95ca to your computer and use it in GitHub Desktop.
Save samuel-mellert/e693240229abd44b95ca to your computer and use it in GitHub Desktop.
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
default:
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