Skip to content

Instantly share code, notes, and snippets.

@mntone
Created August 15, 2019 05:43
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 mntone/9d742a1cbe18743e21c071600990c5d0 to your computer and use it in GitHub Desktop.
Save mntone/9d742a1cbe18743e21c071600990c5d0 to your computer and use it in GitHub Desktop.
Apply font style (bold / italic) & features (monospaced digit).
import CoreText
import class UIKit.UIFont
import class UIKit.UIFontDescriptor
extension UIFont {
public func asBold() -> UIFont? {
return asTraits(.traitBold)
}
public func asItaric() -> UIFont? {
return asTraits(.traitItalic)
}
private func asTraits(_ traits: UIFontDescriptor.SymbolicTraits) -> UIFont? {
guard let fontDesc = self.fontDescriptor.withSymbolicTraits(traits) else { return nil }
return UIFont(descriptor: fontDesc, size: 0)
}
public func asMonospacedDigit() -> UIFont {
return customized(by: [
.typeIdentifier: kNumberSpacingType,
.featureIdentifier: kMonospacedNumbersSelector,
])
}
public func customized(by features: [UIFontDescriptor.FeatureKey: Any]) -> UIFont {
let fontDesc = self.fontDescriptor.addingAttributes([.featureSettings: features])
return UIFont(descriptor: fontDesc, size: 0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment