Created
June 16, 2018 12:22
-
-
Save warren-gavin/4da0aadc2919a2a3e7f047030137f720 to your computer and use it in GitHub Desktop.
Get the UIFont.TextStyle that a font was created with
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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