Skip to content

Instantly share code, notes, and snippets.

@warren-gavin
Created June 16, 2018 12:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save warren-gavin/4da0aadc2919a2a3e7f047030137f720 to your computer and use it in GitHub Desktop.
Save warren-gavin/4da0aadc2919a2a3e7f047030137f720 to your computer and use it in GitHub Desktop.
Get the UIFont.TextStyle that a font was created with
// Fonts can be created with UIFont.preferredFont(forTextStyle:), but there's
// no direct way to find out what textStyle a font was created with.
//
// Requires: Swift 4.2, iOS 11
extension UIFont {
// Can be nil if the font was created using another method other than UIFont.preferredFont(forTextStyle:)
var textStyle: TextStyle? {
guard let styleName = fontDescriptor.fontAttributes[.textStyle] as? String else {
return nil
}
let textStyle = TextStyle(rawValue: styleName)
return TextStyle.allCases.contains(textStyle) ? textStyle : nil
}
}
extension UIFont.TextStyle: CaseIterable {
public static var allCases: [UIFont.TextStyle] {
return [
.largeTitle,
.title1,
.title2,
.title3,
.headline,
.subheadline,
.body,
.callout,
.footnote,
.caption1,
.caption2
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment