Created
November 24, 2023 19:01
-
-
Save frankrausch/a4a3bc1b43e6f144aff96eacc9529790 to your computer and use it in GitHub Desktop.
A Swift modifier to get the monospaced high legibility figures
This file contains 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
import UIKit | |
import SwiftUI | |
extension View { | |
func highLegibilityFigures(forStyle style: UIFont.TextStyle, tableFigures: Bool = false) -> some View { | |
modifier(HighLegibilityFigures(style: style, tableFigures: tableFigures)) | |
} | |
} | |
private struct HighLegibilityFigures: ViewModifier { | |
var style: UIFont.TextStyle = .body | |
var tableFigures: Bool = false | |
func body(content: Content) -> some View { | |
content | |
.font(HighLegibilityFigures.highLegibilityForStyle(style, tableFigures: tableFigures)) | |
} | |
static func highLegibilityForStyle(_ style: UIFont.TextStyle, tableFigures: Bool) -> Font { | |
var attributes = [ | |
UIFontDescriptor.AttributeName.featureSettings: [ | |
[ // High legibility 6 and 9 | |
UIFontDescriptor.FeatureKey.type: kStylisticAlternativesType, | |
UIFontDescriptor.FeatureKey.selector: kStylisticAltOneOnSelector | |
], | |
[ // High legibility 4 | |
UIFontDescriptor.FeatureKey.type: kStylisticAlternativesType, | |
UIFontDescriptor.FeatureKey.selector: kStylisticAltTwoOnSelector | |
] | |
] | |
] | |
if tableFigures { | |
attributes[UIFontDescriptor.AttributeName.featureSettings]?.append( | |
[ | |
UIFontDescriptor.FeatureKey.type: kNumberSpacingType, | |
UIFontDescriptor.FeatureKey.selector: kMonospacedNumbersSelector | |
] | |
) | |
} | |
let fontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: style) | |
let descriptor = fontDescriptor.addingAttributes(attributes) | |
let fontSize = fontDescriptor.pointSize | |
let uiFont = UIFont(descriptor: descriptor, size: fontSize) | |
let swiftUIFont = Font(uiFont) | |
return swiftUIFont | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment