Skip to content

Instantly share code, notes, and snippets.

@ole
Last active October 7, 2016 14:45
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 ole/4ffad27ea57834252e2154821ec6409e to your computer and use it in GitHub Desktop.
Save ole/4ffad27ea57834252e2154821ec6409e to your computer and use it in GitHub Desktop.
Fonts with monospaced (tabular) digits
// Adopted from: http://stackoverflow.com/a/19976535/116862 by http://stackoverflow.com/users/2547229/benjohn.
import PlaygroundSupport
import UIKit
let baseFont = UIFont.preferredFont(forTextStyle: .body)
let baseDescriptor = baseFont.fontDescriptor
let proportionalFeatures = [
[
UIFontFeatureTypeIdentifierKey: kNumberSpacingType as NSNumber,
UIFontFeatureSelectorIdentifierKey: kProportionalNumbersSelector as NSNumber
]
]
let proportionalAttributes = [UIFontDescriptorFeatureSettingsAttribute: proportionalFeatures]
let proportionalDescriptor = baseDescriptor.addingAttributes(proportionalAttributes)
let proportionalFont = UIFont(descriptor: proportionalDescriptor, size: baseFont.pointSize)
let monospacesFeatures = [
[
UIFontFeatureTypeIdentifierKey: kNumberSpacingType as NSNumber,
UIFontFeatureSelectorIdentifierKey: kMonospacedNumbersSelector as NSNumber
]
]
let monospacedAttributes = [UIFontDescriptorFeatureSettingsAttribute: monospacesFeatures]
let monospacedDescriptor = baseDescriptor.addingAttributes(monospacedAttributes)
let monospacedFont = UIFont(descriptor: monospacedDescriptor, size: baseFont.pointSize)
let label1 = UILabel(frame: CGRect(x: 20, y: 20, width: 260, height: 90))
label1.numberOfLines = 0
label1.font = proportionalFont
label1.text = "Proportional digits:\n11111\n22222"
let label2 = UILabel(frame: CGRect(x: 20, y: 130, width: 260, height: 90))
label2.numberOfLines = 0
label2.font = monospacedFont
label2.text = "Monospaced digits:\n11111\n22222"
let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 400))
view.addSubview(label1)
view.addSubview(label2)
PlaygroundPage.current.liveView = view
@ole
Copy link
Author

ole commented Oct 7, 2016

Result:

screen shot 2016-10-07 at 16 43 32

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment