Skip to content

Instantly share code, notes, and snippets.

@liorazi
Last active November 23, 2024 13:14
Show Gist options
  • Save liorazi/94e85f36e97908716e48f0ebb0ac753a to your computer and use it in GitHub Desktop.
Save liorazi/94e85f36e97908716e48f0ebb0ac753a to your computer and use it in GitHub Desktop.
Font Extension for Monospaced Digits (Swift 4.0)
import UIKit
extension UIFont {
/// Returns a font with monospaced digits, preserving other font attributes.
var withMonospacedDigits: UIFont {
let monospacedDescriptor = fontDescriptor.withMonospacedDigits
return UIFont(descriptor: monospacedDescriptor, size: 0) // Size 0 preserves the original font size.
}
}
private extension UIFontDescriptor {
/// Returns a font descriptor with monospaced digits feature enabled.
var withMonospacedDigits: UIFontDescriptor {
let featureSettings = [
[UIFontDescriptor.FeatureKey.type: kNumberSpacingType,
UIFontDescriptor.FeatureKey.selector: kMonospacedNumbersSelector]
]
return addingAttributes([.featureSettings: featureSettings])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment